簡體   English   中英

將多個范圍傳遞給關注方法-Ruby on Rails

[英]Passing multiple scopes to Concern Method - Ruby on Rails

在干燥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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM