尝试编写一个插件,我需要检查用户是否具有特定权限。例如,我正在考虑这样的事情
if (user.current has "view_private_notes" )
do something
end
尝试编写一个插件,我需要检查用户是否具有特定权限。例如,我正在考虑这样的事情
if (user.current has "view_private_notes" )
do something
end
检查用户模型。您想要的几乎完全一样:
# 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)
您可以通过插件扩展现有模型并添加您喜欢的方法来组合现有的:
//init.rb
ActionDispatch::Callbacks.to_prepare do
unless User.included_modules.include?(MyPlugin::UserPatch)
User.send(:include, MyPlugin::UserPatch)
end
end
//user_patch.rb 是这样的:
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
实际上,使用现有方法很容易。
if User.current.allowed_to?(:view_private_notes, @project)
puts "i know what you did!"
end