Module: Credentials::Extensions::ActionController::ClassMethods
- Defined in:
- lib/credentials/extensions/action_controller.rb
Instance Method Summary collapse
-
#current_user_method(value = nil) ⇒ Object
(also: #current_user_method=)
Sets the method for determining the current user in a controller instance.
-
#required_credentials ⇒ Object
:nodoc:.
-
#requires_permission_to(*args) ⇒ Object
Specify a requirement for the currently logged-in user to be able to access particular actions.
Instance Method Details
#current_user_method(value = nil) ⇒ Object Also known as: current_user_method=
Sets the method for determining the current user in a controller instance. (Default: :current_user)
64 65 66 |
# File 'lib/credentials/extensions/action_controller.rb', line 64 def current_user_method(value = nil) rw_config(:current_user_method, value, :current_user) end |
#required_credentials ⇒ Object
:nodoc:
57 58 59 |
# File 'lib/credentials/extensions/action_controller.rb', line 57 def required_credentials #:nodoc: read_inheritable_attribute(:required_credentials) || [] end |
#requires_permission_to(*args) ⇒ Object
Specify a requirement for the currently logged-in user to be able to access particular actions.
The current user is determined by calling the method named in self.class.current_user_method (default is current_user). If there is a rule set against the current action and no user is logged in, then a Credentials::Errors::NotLoggedInError is raised.
Otherwise, the rules are treated like ‘before’ filters, with the result being either a pass (action is executed as normal) or a failure (Credentials::Errors::AccessDeniedError is raised). (Note that evaluation stops at the first failure.)
Just like ActionController’s built-in filters, you can use only and unless to restrict the scope of your rules.
Credential tests
For the most part, these are carried out as you’d expect:
:create, Post
# checks current_user.can? :create, Post
However, the magic part is that any symbol arguments are evaluated against the current controller instance, if matching methods can be found, allowing you to do this:
class PostsController
:edit, :current_post,
:only => %w(edit update destroy)
def edit
# ...
end
protected
def current_post
@current_post ||= Post.find params[:id]
end
end
Note that for this to work, the current_post method must be declared protected. The reason for this is that otherwise Credentials would also try to evaluate the edit method as an argument.
49 50 51 52 53 54 55 |
# File 'lib/credentials/extensions/action_controller.rb', line 49 def (*args) = (args.last.is_a?(Hash) ? args.pop : {}) [ :only, :except ].each do |key| [key] = Array([key]).map(&:to_sym) if [key] end self.required_credentials = self.required_credentials + [ [ , args ] ] end |