Retrieve duration (in string format) from database and convert to Ruby syntax for calculation

If I store 1.month as a string in the database, how do I convert
“1.month”
into 1.month?

This way I can use the “1.month” value stored in database to perform the
following calculation.

Time.now + 1.month

I don’t think this is good idea. 1.month.to_i will return in seconds
as 2592000. you can store this and while fetching you can use it as it
is
Time.now + 2592000

btw you can do it using “eval” like eval(“1.month”)

Take a look at this gem: GitHub - josedonizetti/ruby-duration: Immutable type that represents some amount of time with accuracy in seconds.
it will convert an arbitrary duration (like 1 month, 2 weeks, etc.) into
seconds which can be stored in the DB. It is very similar to what Raj is
recommending, just a little more formal. Either way you can avoid
eval’ing
code, and your calculation can be a lot more flexible.

On 20 September 2013 08:30, Fai W. [email protected] wrote:

If I store 1.month as a string in the database, how do I convert “1.month”
into 1.month?

This way I can use the “1.month” value stored in database to perform the
following calculation.

Time.now + 1.month

If you really feel you need to do this then you can store “1.month” as
a string and use eval

1.9.3p194 :007 > delta = “1.month”
=> “1.month”
1.9.3p194 :008 > Time.now
=> 2013-09-22 08:52:13 +0100
1.9.3p194 :009 > Time.now + eval( delta )
=> 2013-10-22 08:52:23 +0100

However if you do this be /very/ careful about what can get into the
database as arbitrary code can be executed using eval and conceivably
your machine could be hacked. I DO NOT recommend that you do this.
If your requirement is for a delta with values such as 1 month 3 weeks
and so on, then I suggest having two fields, one for the quantity and
an enumerated value for the period (month, week and so on). Then work
it out in code. Less efficient but /much/ safer.

Colin

But not all months are 2592000 seconds long…some are shorter and
some are longer…
If you have a Date of 1 Jan and add 1.month to it you will get 1 Feb
which is 31 days later. If you have 1 Feb and you add 1.month you will
get 1 Mar which is 28 or 29 days later.

You could just store the value as x so you could do Time.now + x.month

Norm

Thanks for your help everyone.

I ended up using Chronic Duration gem.