mongoid/created_at: add setter

This commit is contained in:
Jörg Thalheim 2014-11-20 16:40:46 +01:00
parent d976a8f504
commit 69e35aeb71

View File

@ -10,24 +10,38 @@ categories:
description: "Mongoid: Use ObjectId as created_at" description: "Mongoid: Use ObjectId as created_at"
--- ---
**Update: Nov 20 2014:** add setter
One great feature of Mongodb is, that the first bytes of each ObjectID contains the time, they were generated. One great feature of Mongodb is, that the first bytes of each ObjectID contains the time, they were generated.
This can be exploited to mimic the well known `created_at` field in rails. This can be exploited to mimic the well known `created_at` field in rails.
First put this file in your lib directory. First put this file in your lib directory.
```ruby ```ruby
#lib/mongoid/created.rb #lib/mongoid/created.rb
module Mongoid module Mongoid
module CreatedAt module CreatedAt
# Returns the creation time calculated from ObjectID # Returns the creation time calculated from ObjectID
# #
# @return [ Date ] the creation time # @return [ Date ] the creation time
def created_at def created_at
id.generation_time id.generation_time
end end
# Set generation time of ObjectId.
# Note: This will modify the ObjectId and
# is therefor only useful for not persisted documents
#
# @return [ BSON::ObjectId ] the generated object id
def created_at=(date)
self.id = BSON::ObjectId.from_time(date)
end
end end
end end
``` ```
If you are still using mongoid 3 replace `BSON::ObjectId` with `Moped::BSON::ObjectId`.
Now you can include this module in every Model, where you need created at. Now you can include this module in every Model, where you need created at.
```ruby ```ruby
@ -37,7 +51,7 @@ class User
include Mongoid::CreatedAt include Mongoid::CreatedAt
# ... # ...
end end
u = User.new u = User.new(created_at: 1.hour.ago)
u.created_at u.created_at
``` ```