Reputation: 265
Trying to write a plug-in for which I need to check if the user has a particular permission . For example I am thinking of something like this
if (user.current has "view_private_notes" )
do something
end
Upvotes: 3
Views: 1340
Reputation: 4865
if User.current.allowed_to?(:view_private_notes, @project)
puts "i know what you did!"
end
Upvotes: 3
Reputation: 770
Check User model. There is near exact you want:
# Return true if the user is allowed to do the specified action on a specific context
# Action can be:
# * a parameter-like Hash (eg. :controller => 'projects', :action => 'edit')
# * a permission Symbol (eg. :edit_project)
# Context can be:
# * a project : returns true if user is allowed to do the specified action on this project
# * an array of projects : returns true if user is allowed on every project
# * nil with options[:global] set : check if user has at least one role allowed for this action,
# or falls back to Non Member / Anonymous permissions depending if the user is logged
def allowed_to?(action, context, options={}, &block)
You can extend existing models by your plugin and add methods you like combining existing:
//init.rb
ActionDispatch::Callbacks.to_prepare do
unless User.included_modules.include?(MyPlugin::UserPatch)
User.send(:include, MyPlugin::UserPatch)
end
end
//user_patch.rb Something like this:
def self.included(base)
base.class_eval do
unloadable
# need to pass context to be able trigger allowed_to method in old way.
has_right_view_project(project,context)
self.allowed_to?({:controller => context[:controller], :action => context[:action]}, project, :global => true)
end
end
Actually it's easy to use existing methods.
Upvotes: 4