Sha256: 9a01f01b500ff6b64c37ac4fe835602055dac7eac20e5f7ac148ef66cda769b4

Contents?: true

Size: 1.5 KB

Versions: 1

Compression:

Stored size: 1.5 KB

Contents

require 'dm-aggregates'
module Ixtlan
  module DataMapper
    module ConditionalGet

      def self.included(base)
        base.extend ConditionalGet
      end

      private

      ONE_SECOND = 1.0/86400

      def _conditional_get( method, modified_since, *id )
        if modified_since.is_a? String
          modified_since = DateTime.parse( modified_since.sub(/[.][0-9]+/, '') )
        end
        if modified_since.nil?
          self.send( method, *id )
        else
          modified_since = modified_since.new_offset( 0 )
          query = Hash[ key.collect { |k| k.name }.zip( id ) ]
          query[ :updated_at.gt ] = modified_since
          query[ :updated_at.lt ] = modified_since + ONE_SECOND
          # return false when up-to-date
          # that helps to distinguish from nil which means not-found
          self.count( query ) == 0 ? self.send( method, *id ) : false
        end
      end

      public

      def conditional_get!( modified_since, *id )
        _conditional_get( :get!, modified_since, *id )
      end

      def conditional_get( modified_since, *id )
        _conditional_get( :get, modified_since, *id )
      end
    end
    ::DataMapper::Model.append_inclusions( ConditionalGet )
    ::DataMapper::Associations::OneToMany::Collection.send( :include,
                                                            ConditionalGet )
    ::DataMapper::Associations::ManyToMany::Collection.send( :include,
                                                             ConditionalGet )
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
ixtlan-datamapper-0.1.0 lib/ixtlan/datamapper/conditional_get.rb~