marcamillion marcamillion - 1 year ago 76
Ruby Question

How do I use the value stored in a variable as a method call?

I have a method that looks like this:

> rating
=> "speed"

Then I have a call that looks like this:

profile.ratings.find_by(user: current_user).speed

What I want to do is pass the value of
to that call.

But when I do this:

profile.ratings.find_by(user: current_user).rating

It doesn't work, because there is no method called
on each

This is the error I get when I run the above:

Rating Load (4.5ms) SELECT "ratings".* FROM "ratings" WHERE "ratings"."profile_id" = $1 AND "ratings"."user_id" = 7 LIMIT $2 [["profile_id", 12], ["LIMIT", 1]]
NoMethodError: undefined method `rating' for #<Rating:0x007fca0c4fba90>

I would normally do string interpolation, except now I am working on a method call.

How might I do this?

Answer Source

If you're looking to access a property on an ActiveRecord model they provide a simple accessor:

profile.ratings.find_by(user: current_user)[rating]

This is safer than the send method since it's only going to fetch attributes. If you had a method called ban_and_charge_ten_bucks! some hostile user might be able your system into calling that if you call send without checking what you're calling.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download