我有一个担忧:
# 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|
included do
...
end
class_methods do
...
end
end
included
但由于有多个块,它不起作用。我可以提取Role.find_each
方法,但也好不到哪里去。
如何改进此代码并消除重复?