[英]Define class and instance methods dynamically in concern
我有一個問題:
# app/models/concerns/rolable.rb
module Rolable
extend ActiveSupport::Concern
included do
rolify
Role.find_each do |role|
scope "#{role.name.pluralize}", -> { joins(:roles).where(roles: {name: send("#{role.name}_role_name")}).distinct }
end
end
class_methods do
Role.find_each do |role|
define_method "#{role.name}_role_name" do
role.name
end
define_method "#{role.name}_role_id" do
role.id
end
end
end
Role.find_each do |role|
define_method("#{role.name}?") do
has_role? self.class.send("#{role.name}_role_name")
end
end
end
如您所見,它定義了一堆范圍,類方法和實例方法。 但是我對重復Role.find_each do |role| ... end
感到高興 Role.find_each do |role| ... end
我怎樣才能消除這種重復? 我試過這個
Role.find_each do |role|
included do
...
end
class_methods do
...
end
end
但由於多個included
塊,它不起作用。 我可以在方法中提取Role.find_each
,但它並沒有好多少。
如何改進此代碼並刪除重復?
我認為你的邏輯錯誤。 您不應該使用Role.find_each
因為在初始化基類之后新角色將不可用,或者您必須在每次需要時明確加載您的關注點。
在rolify中,您有一些有用的方法:
Forum.with_role(:admin)
Forum.with_role(:admin, current_user)
@user.has_role?(:forum, Forum)
...
如果您非常確定您的角色庫存不會擴展,那么您可以動態定義一堆匿名問題,而不是為所有角色創建一個問題。
# models/concerns/rolables.rb
# no need to call `find_each' because the number or roles will never exceed 1000
Rolables = Role.all.map do |role|
Module.new do
extend ActiveSupport::Concern
included do
scope "#{role.name.pluralize}", -> { joins(:roles).where(roles: {name: send("#{role.name}_role_name")}).distinct }
define_method("#{role.name}?") do
has_role? self.class.send("#{role.name}_role_name")
end
end
class_methods do
define_method "#{role.name}_role_name" do
role.name
end
define_method "#{role.name}_role_id" do
role.id
end
end
end
end
並將所有這些問題包含在您的模型中:
# models/user.rb
class User
Rolables.each{|concern| include concern}
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.