开发者

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

开发者 https://www.devze.com 2023-01-08 23:03 出处:网络
Okay, so I need something like this: time_span = \"1.month\" date = DateTime.now date = date + send(\"#{time_span}\")

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 nu开发者_开发技巧mber 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.


Try using:

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


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号