views:

1036

answers:

3

In Ruby, I'm trying to do the following.

def self.stats(since)
  return Events.find(:all, :select => 'count(*) as this_count', :conditions => ['Date(event_date) >= ?', (Time.now - since)]).first.this_count
end

where "since" is a string representing an amount of time ('1 hour', '1 day', '3 days') and so on. Any suggestions?

+2  A: 

Try using Chronic to parse the date strings into actual datetime objects.

John Millikin
+2  A: 

I hacked this together with the ActiveSupport gem:

require 'active_support'

def string_to_date(date_string)
  parts = date_string.split
  return parts[0].to_i.send(parts[1])
end
sinces = ['1 hour', '1 day', '3 days']

sinces.each do |since|
  puts "#{since} ago: #{string_to_date(since).ago(Time.now)}"
end

[edit] To answer your question, you might try it like that:

:conditions => ['Date)event_date) >= ?', (string_to_date(since).ago(Time.now))]
wieczo
A: 

I especially like the string_to_date(var).ago(Time.now) pattern.. thanks!

aronchick
You might have added a comment to wieczo's answer rather than adding a new answer
glenn jackman
I think i did this before comments had been implemented. Guessing though.
aronchick