riffraff asked:

How to select all objects created today?

I have an Og managed class which is Timestamped, and I’d like to find all the object that have been created in the current day, but I don’t have any clue on how to do this, especially because the automatical fields created by Timestamped are Datetime, so I can’t just check them with an equality constraint.

Is it possible to do a select/find playing with time? Otherwise, would it be possible to coerce Timestamped to use Date fields?

I’m working with glycerin but I think the same applies for any version of Og.

(3 attempts)

Kashia answered:

Very nice answer there, Goku2.

In my opinion, the database should handle the "created today" constraint though.

One possible solution (only PostgreSQL) (maybe such stuff could be added to Og):

def self.all_created_today(options = {})
  return self.class.created_days_ago(0)
end

def self.created_days_ago(days, options = {})
  options = {
    :condition => "date_trunc('day', create_time) = date_trunc('day', now() - '#{days} days'::interval)"
  }.update(options)
  
  return self.find(options)
end

Of course this could be made a lot more useful, this is just a quick fix.

This pushes more logic to the DB, however, by doing that it avoids getting the whole table from the database when you just want the ones from a single day (think about bigger apps...). I made the interface like Goku2's so you might be able to just "drop it in" (provided you use PostgreSQL).

Rating: 5

goku2 answered:

This isn't an optimal solution but the logic is in the model and it works 4 me :D

The model code:

class Product
 property :name

 is Timestamped

 def self.all_created_today
   all.select { |p| p.created_today? }
 end

 def created_today?
  create_date = [@create_time.day, @create_time.month,              
                 @create_time.year]
  today = Time.now
  today_date = [today.day, today.month, today.year]    
  return create_date == today_date
 end
end

So Product.allcreatedtoday retrieves an array of product created today.

i hope it helps :)

Rating: 4

Rayman answered:

as a fan of eZ, I'd try the following:

class Job
  property :name, String
  is Timestamped

  def self.todays_jobs
    self.find {|e| e.create_time.to_date == Date.today}
  end
end

you might need to require facet time/date classes for the to_date to work. And the code probably needs some tweaking to work.

Rating: 0