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
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!