0

How to pass a string literal to a ruby method? (Rails 2.3.8) I want to achieve something like the below example:

 Class.find_by_"#{params[:column]}"
Stacked-for-life
  • 196
  • 2
  • 17
  • 1
    possible duplicate of [How to invoke a method in ruby when method name is dynamic?](http://stackoverflow.com/questions/16749952/how-to-invoke-a-method-in-ruby-when-method-name-is-dynamic) –  May 08 '14 at 21:05

3 Answers3

1

You can use .send("your_method", *your_args):

1.9.3p489 :027 > Object.send("try", :to_s)
 => "Object" 

In your case:

Model.send("find_by_#{params[:column]}", params[:search_string])

Also, I highly recommend you to put some security checks on this:

if Model.column_names.include?(params[:column].to_s)
  Model.send("find_by_#{params[:column]}", params[:search_string])
else
  # usually return nil or empty scope like `Model.where('FALSE')`
end

This will prevent from using non-existing columns, and provoke a internal error in your app.

MrYoshiji
  • 54,334
  • 13
  • 124
  • 117
1

In Rails 4 - this should work:

column_name = params[:column]
Class.find_by column_name.to_sym => value
Kalman
  • 8,001
  • 1
  • 27
  • 45
1

Try:

Class.send(:"find_by_#{params[:column]}", value)
BroiSatse
  • 44,031
  • 8
  • 61
  • 86
  • Why do you change `params[:column]` to string then to symbol? – MrYoshiji May 08 '14 at 21:08
  • @MrYoshiji - params[:column] is a string, so I'm not turning it into a string. I prefer passing symbols instead of strings to `send`, hence I am converting it to a symbol. – BroiSatse May 08 '14 at 21:12