Skip to content

Instantly share code, notes, and snippets.

@durran
Created December 23, 2011 22:14
Show Gist options
  • Save durran/1515507 to your computer and use it in GitHub Desktop.
Save durran/1515507 to your computer and use it in GitHub Desktop.
Customize Mongoid to persist times as integers +/- epoch.
module Windows
class Time
include Mongoid::Fields::Serializable
def deserialize(time)
Time.at(time)
end
def serialize(time)
time.to_i
end
end
end
class Foo
include Mongoid::Document
field :time, type: Windows::Time
end
@durran
Copy link
Author

durran commented Dec 23, 2011

You will see when you save, Mongoid will store in seconds pre or post epoch:

Foo.create(time: Time.now)
#=> MONGODB mongoid_sandbox['foos'].insert([{"time"=>1324481141, "_id"=>BSON::ObjectId('4ef1fa758ad548115a000001')}])
Foo.create(time: 50.years.ago)
#=> MONGODB mongoid_sandbox['foos'].insert([{"time"=>-253355659, "_id"=>BSON::ObjectId('4ef1fa758ad548115a000002')}])

And when you query, Mongoid will convert as well:

Foo.where(:time.gt => 30.years.ago).to_a
#=> MONGODB mongoid_sandbox['foos'].find({:time=>{"$gt"=>377796341}})
#=> [#<Foo _id: 4ef1fa758ad548115a000001, _type: nil, time: 1324481141>]

Foo.where(:time.lt => 30.years.ago).to_a
#=> MONGODB mongoid_sandbox['foos'].find({:time=>{"$lt"=>377796341}})
#=> [#<Foo _id: 4ef1fa758ad548115a000002, _type: nil, time: -253355659>]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment