mr. jman mr. jman - 9 months ago 23
Ruby Question

Rails: Calculate time using time identifier stored in database as "string"

I would like to calculate future dates like this: + 1.year + 1.month

To determine, if the future date needs to be one
or one
into the future I request the
from a database. The
value is saved as a string.

end_date = + 1.Duration.find(order.duration_id).duration

I believe that the above code executes as follows: + 1."year" #the quotes cause an error

How do I remove the quotes?


In rails, the way 1.year works, is :year is an instance method on 1. In ruby, to evaluate an arbitrary method on an object, you just use send('method_name') or send(:method_name)

If you have your duration as a string, you can use :send to evaluate the actual duration:

duration = "year"
1.send(duration) == 1.year