Assume the require_role ["alt", "student worker"], :except => [:list, :show, :index, :create]
works outside of this method, what am I doing wrong here? When I call the method it works while it is a promo_site? (true), but when it is false the method fails.
def check_if_role_is_required
require_role ["alt"开发者_开发知识库, "student worker"], :except => [:list, :show, :index, :create] unless promo_site?
end
Ambiguous question, so this is only speculation:
At a glance it looks like require_role is a wrapper for a before_filter. So I'm going to base my answer off that observation.
before_filter is a controller class method. As opposed to check_if_role_required which appears to be a controller instance method. Because require_role appears to be a wrapper for before_filter, I'm going to assume that's also a class method.
When ever you call a bare method (not called by an object) Ruby implicitly determines the calling object to be self. Which works out to be the defining class for method calls appearing outside methods, or the object calling the current method for method calls inside other methods. In the case of class methods, self is the current class. When it comes to before_filter, it expects to be called by the ActionController::Base class. By calling it inside an instance method, such as check_if_role_required, the self evaluates to an instance of ActionController::Base which does not have before_filter or possibly even require_role defined.
Code always helps cement examples:
This simple class helps illustrate my point.
class Example
# class method like required_role or before_filter
def self.c_method
# calls self.class
# self is the class Example
class
end
c_method # valid statement
#instance method like check_if_role_required
def i_method
#calls self.class
# self is an instance of the Example class.
class
end
# invalid statement
# i.method
def missing_method_example
# raises error.
# calls self.c_method, but self is the instance.
# c_method is not defined for instances of Example
c_method
end
end
Example.c_method # => "Class"
@example = Example.new
@example.i_method # => "Example"
@example.missing_method_example # => Unknown Method Error
Try to wrap your parameters in parenthesis:
require_role(["alt", "student worker"], :except => [:list, :show, :index, :create]) unless promo_site?
This often fixes such issues where hashes are involved...
精彩评论