0

Just a very simple question, I have a module inside lib folder in rails.

On that module, if we do something like Company.accessible_by(current_ability) we got a name error where current_ability is undefined.

Anybody know the solution to this? As current_ability seems only recognized in controller.

hudarsono
  • 389
  • 4
  • 19

1 Answers1

0

You need to pass in the current_ability into the module. As with session and parameter data (and current_user if you are using devise) you have no way of accessing these inside models or classes you created on your own.

That's actually a good thing as you don't want your business objects to be dependent on the web stack. The general way with these things (also applies to models) is either to construct the object with a reference to a current_ability you pass in, or on the method call itself. Here is some sample code:

class Foo
  def initialize(ability)
     @current_ability = ability
  end

  def list_companies
    Company.accessible_by(@current_ability)
  end
end

Or if you only need it in one call:

class Foo
  def list_companies(current_ability)
    Company.accessible_by(current_ability)
  end
end

Both cases are perfectly valid, and allow you to easily test the code with a Mock ability object.

Tigraine
  • 23,358
  • 11
  • 65
  • 110