Sha256: 3abadbcaa8c204f9b3de21014484ccbeb353c95c888fd73448bd6cad9048d8a3

Contents?: true

Size: 1.73 KB

Versions: 22

Compression:

Stored size: 1.73 KB

Contents

module MongoDoc
  module Timestamps

    # 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
    def timestamps!
      [:created_at, :updated_at].each do |name|
        _keys << name unless _keys.include?(name)
        attr_reader name
        module_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

      module_eval do
        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
          super
        rescue Mongo::MongoDBError => e
          self.updated_at = original_updated_at
          raise e
        end
      end
    end
  end
end

Version data entries

22 entries across 22 versions & 1 rubygems

Version Path
mongo_doc-0.6.26 lib/mongo_doc/timestamps.rb
mongo_doc-0.6.25 lib/mongo_doc/timestamps.rb
mongo_doc-0.6.23 lib/mongo_doc/timestamps.rb
mongo_doc-0.6.22 lib/mongo_doc/timestamps.rb
mongo_doc-0.6.21 lib/mongo_doc/timestamps.rb
mongo_doc-0.6.20 lib/mongo_doc/timestamps.rb
mongo_doc-0.6.19 lib/mongo_doc/timestamps.rb
mongo_doc-0.6.18 lib/mongo_doc/timestamps.rb
mongo_doc-0.6.17 lib/mongo_doc/timestamps.rb
mongo_doc-0.6.16 lib/mongo_doc/timestamps.rb
mongo_doc-0.6.15 lib/mongo_doc/timestamps.rb
mongo_doc-0.6.14 lib/mongo_doc/timestamps.rb
mongo_doc-0.6.13 lib/mongo_doc/timestamps.rb
mongo_doc-0.6.12 lib/mongo_doc/timestamps.rb
mongo_doc-0.6.11 lib/mongo_doc/timestamps.rb
mongo_doc-0.6.10 lib/mongo_doc/timestamps.rb
mongo_doc-0.6.9 lib/mongo_doc/timestamps.rb
mongo_doc-0.6.8 lib/mongo_doc/timestamps.rb
mongo_doc-0.6.7 lib/mongo_doc/timestamps.rb
mongo_doc-0.6.6 lib/mongo_doc/timestamps.rb