在我的一个项目中,我开始使用专家gem,我有一个非常简单的策略,如下所示:
class CompanyPolicy < ApplicationPolicy
def index?
true if user.is_a? Administrator
end
def new?
true if user.is_a? Administrator
end
def create?
new?
end
def edit?
true if user.is_a? Administrator
end
def update?
edit?
end
end
问题是,我如何避免重复这一点:
true if user.is_a? Administrator
发布于 2015-02-16 12:15:02
我做的把戏看起来是这样的:
class ApplicationPolicy
private
def self.permit_owner_to(*actions)
actions.each do |action|
define_method("#{action}?") do
owner?
end
end
end
def owner?
# owner logic
end
end
并将其用于其他策略。
class ItemPolicy < ApplicationPolicy
permit_owner_to :show, :update, :destroy, :confirm
end
发布于 2015-02-16 09:37:42
我不认为你真的需要移除这个。通过重复此操作,您将显式地表示,此用户必须是访问此方法的管理员。如果您确实想这样做,您可以创建一个私有方法。
class CompanyPolicy < ApplicationPolicy
def index?
admin?
end
def new?
admin?
end
def create?
new?
end
def edit?
admin?
end
def update?
edit?
end
private
def admin?
user.is_a? Administrator
end
end
我想这是个人偏好的问题。
发布于 2015-11-20 03:05:41
你可以用alias_method
。
class CompanyPolicy < ApplicationPolicy
def index?
user.is_a? Administrator
end
alias_method :create?, :index?
alias_method :update?, :index?
end
您有一个基类ApplicationPolicy
,它可能已经包含:
def new?
create?
end
def edit?
update?
end
因此,您不需要在子类中重复这些方法。
.is_a?
返回true
或false
,因此不需要显式返回true if true
。
这要简洁得多,嗯?)
https://stackoverflow.com/questions/28536686
复制相似问题