Search code examples
ruby-on-rails-3scopes

Trying to find a good way to chain scopes dynamically


I found this article on cleaning up chained scopes that would be great in a project I'm working on. However, some of my scopes have arguments. I can't think of a way to make this work with arguments. I tried string interpolation which I suspected wouldn't work and of course, didn't.

https://www.sitepoint.com/dynamically-chain-scopes-to-clean-up-large-sql-queries/

def self.send_chain(methods)
  methods.inject(self, :send)
end

$ methods = ["with_author", "pending_review", "draft", "flagged", "published", "with_website", "with_meta_title", "with_meta_description"]
$ Article.send_chain(methods)

Solution

  • def send_chain(methods)
      methods.inject(self) { |result, method| result.send(*method) }
    end
    

    Methods should be an array, and if a method needs an argument or several arguments, that should be a sub-array

    [:foo, [:bar, "argument"], :baz]