warder57
warder57

Reputation: 350

Rails: Is it possible to check if a named scope is valid for a given active record?

I'm Using Ruby 1.8.7-p374 and Rails 2.3.18. (Yeah, I know, we're working on it.)

I'm considering dynamically passing a named scope to be used as a condition for an ActiveRecord. Is it possible to check to see if a passed string is a valid named scope for the record?

For Example:

If I have a named scope called :red defined for Car

named_scope :red, :condition => ["color = ?", "red"]

Then is there some function where I could do

Car.some_function("red")   # returns true
Car.some_function("blue")  # returns false

Upvotes: 2

Views: 4092

Answers (3)

prcoder
prcoder

Reputation: 164

Check if your scope is present in this list to verify. MyKlass.send(:generated_relation_methods).instance_methods

Upvotes: 0

MrYoshiji
MrYoshiji

Reputation: 54882

You can use .respond_to?(:method) (documentation here)

In your case :

Car.respond_to?(:red)  # => true
Car.respond_to?(:blue) # => false

But you said:

I'm considering dynamically passing a named scope to be used as a condition for an ActiveRecord

I hope you will not use something like this:

# url
/cars?filter=red

# controller
def index
 @cars = Car.send(params[:filter]) if params[:filter].present? && Car.respond_to?(params[:filter])
 @cars ||= Car.find(:all)

Guess what woud happen if I use this URL?

/cars?filter=destroy_all

The Car model responds to the method .destroy_all, so Ruby calls it on the Car model. BOOM, all cars are destroyed!

Upvotes: 8

Max Williams
Max Williams

Reputation: 32945

Klass.scopes will return a hash of all scopes for that class. You can see if it's in there - the names are stored as symbols. eg

if Car.scopes[:red]
  ...

This will return the scope itself (truthy) or nil (falsy), which is fine for passing/failing an if test. If you literally want either true or false back then you can do !! on it to convert it to a boolean.

a_bool = !!Car.scopes[:red]

Upvotes: 3

Related Questions