在干燥Rails应用程序代码的过程中,我创建了以下关注点,用于生成索引方法的内容。
define_method(:generate_index) do |string, scope|
instance_variable_set( "@#{string}", string.camelize.constantize.public_send(scope))
end
我使用此代码生成如下内容:
def index
generate_index("foo", "all")
# @foo = Foo.all
end
我想做的是让define方法接受多个作用域。我尝试传入一组作用域,但结果出现了错误。
有什么想法吗?
感谢
您可以使用splash *
运算符:
define_method(:generate_index) do |klass, *scopes|
scope = klass.to_s.camelize.constantize
scopes.each { |s| scope = scope.send(s) }
instance_variable_set("@#{string}", scope)
end
def index
generate_index(:foo, :all, :where_not_test)
# @foo = Foo.all.where_not_test
end