Christian Bankester
Christian Bankester

Reputation: 2124

Storing dynamic lengths of time on the database in ruby on rails

Okay, so I need something like this:

time_span = "1.month" 
date = DateTime.now 
date = date + send("#{time_span}") 

where time_span is actually stored on the database, but that doesn't seem to work.. Here's some console action:

$ rails c
>> time_span = 1.month
=> 1 month
>> date = DateTime.now + time_span
=> Fri, 27 Aug 2010 20:51:18 -0500
>> time_span.class
=> Fixnum
>> time_span = '1.month'
=> "1.month"
>> date = DateTime.now + time_span
TypeError: expected numeric
    ruby/1.8/date.rb:1236:in `plus_without_duration'
    date/calculations.rb:87:in `+'
    from (irb):5

The idea is that I need to store 1.month as a string in the database because storing 1.month as a fixnum only stores the total number of seconds in that particular month, but I want it to be more dynamic based on the current month. I know send in this case isn't being used as it's documentation suggests, but I have seen it used in this manner.

Upvotes: 0

Views: 316

Answers (3)

joserwan
joserwan

Reputation: 326

Another solution is to serialize 1.month in database.

class User < ActiveRecord::Base
  serialize :preferences
end

see http://api.rubyonrails.org/classes/ActiveRecord/Base.html#M001799

Upvotes: 0

Evan Cordell
Evan Cordell

Reputation: 4118

Try using:

time_span = "1.month"
date = DateTime.now + eval(time_span)

Upvotes: 1

Daniel Vandersluis
Daniel Vandersluis

Reputation: 94123

Instead of send, you probably want eval... but on the other hand, you should probably avoid using eval.

If time_span is always in the form of 1.month (ie. the magnitude and unit separated by a dot), you could parse it out as into an object call:

magnitude, unit = time_span.split('.')
date += magnitude.to_i.send(unit)

Another solution would be to save the magnitude and unit separately in the database, but then do the same thing, send the unit to the magnitude.

Obviously this won't work if the magnitude is not a number or the unit is not one of Rails' ActiveSupport::CoreExtensions::Numeric::Time extensions.

Upvotes: 1

Related Questions