将多个范围传递给Concern方法 - Ruby on Rails

时间:2015-02-12 11:26:04

标签: ruby-on-rails ruby ruby-on-rails-4

在干燥我的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方法接受许多范围。我尝试传入一组范围,但这会导致错误。

有什么想法吗?

由于

1 个答案:

答案 0 :(得分:1)

您可以使用启动*运算符:

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
相关问题