Module: MongoDoc::Timestamps
- Defined in:
- lib/mongo_doc/timestamps.rb
Instance Method Summary collapse
-
#timestamps! ⇒ Object
Create automatic timestamps on a
root
Document.
Instance Method Details
#timestamps! ⇒ Object
Create automatic timestamps on a root
Document. Timestamps are not implemented for embedded documents.
Two timestamps fields are created: created_at
, updated_at
created_at
-
set on initial save only
updated_at
-
set on every save
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
# File 'lib/mongo_doc/timestamps.rb', line 11 def [:created_at, :updated_at].each do |name| _add_key(name) attr_reader name class_eval(<<-RUBY, __FILE__, __LINE__) def #{name}=(value) # def created_at=(value) if value.kind_of?(String) # if value.kind_of?(String) value = Time.cast_from_string(value) # value = Time.cast_from_string(value) end # end @#{name} = value.nil? ? nil : value.utc # @created_at = value.nil? ? nil : value.utc end # end RUBY end class_eval(<<-RUBY, __FILE__, __LINE__) def _save(safe) if new_record? self.created_at = self.updated_at = Time.now else original_updated_at = updated_at self.updated_at = Time.now end super rescue Mongo::MongoDBError => e if new_record? self.created_at = self.updated_at = nil else self.updated_at = original_updated_at end raise e end def _update(selector, data, safe) original_updated_at = updated_at self.updated_at = Time.now data[:updated_at] = updated_at super rescue Mongo::MongoDBError => e self.updated_at = original_updated_at raise e end RUBY end |