marcamillion
marcamillion

Reputation: 33755

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 rating 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 rating on each ratings object.

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?

Upvotes: 1

Views: 53

Answers (2)

tadman
tadman

Reputation: 211560

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.

Upvotes: 4

Ursus
Ursus

Reputation: 30056

You can use the send method

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

Upvotes: 2

Related Questions