mr. jman mr. jman - 7 months ago 15
Ruby Question

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

I would like to calculate future dates like this:

Date.today + 1.year
Date.today + 1.month


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

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


I believe that the above code executes as follows:

Date.today + 1."year" #the quotes cause an error


How do I remove the quotes?

Answer

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