I’m writing a rails script which accepts command line parameters. One param is a relative date – i.e. 3.months.ago
This option is passed to my script as a string. How can I use that string as a relative date? My instinct is to cast it, but not sure to what…
For instance:
>> Event.count(:all, :conditions => ["created_at > ?", 3.months.ago])
=> 18883
>>
>> user_date = "3.months.ago"
>> Event.count(:all, :conditions => ["created_at > ?", user_date])
ActiveRecord::StatementInvalid: PGError: ERROR: invalid input syntax for type timestamp: "3.months.ago"
Just evaluate it to get a Time instance:
Of course, you don’t want to
evalanything that a user inputs directly. But it’s a reasonable way to handle relative dates that you construct.