Philip Bradley
Philip Bradley

Reputation:

How do I make recursive named_scope calls on a Ruby class in Rails?

Suppose I have defined a bunch of named_scopes in a rails Person model. For example:

named_scope :male ...
named_scope :tall
named_scope :short
named_scope :happy

...whatever.

Well, what I'm doing is globbing a bunch of scopes in routes.rb and eventually I have an array of scopes...like this:

scopes = ["male", "happy", "short"]

Now, I know I can do this:

Person.male.happy.short and get the records that fit those scopes.

But I want to be able to do it via the array as a parameter, because as we know we can also do this:

somescope = "male"
result = Person.send(somescope)

which is the same as

result = Person.male

So given an array of scopes, like the "scopes" one above, how can I best get the result

Person.male.happy.short 

from the array

["male", "happy", "short"]

?

mucho appreciated.

Upvotes: 1

Views: 237

Answers (1)

ryanb
ryanb

Reputation: 16287

Try this.

@people = ["male", "happy", "short"].inject(Person) { |person, scope| person.send(scope) }

Upvotes: 1

Related Questions