Sha256: 61714be2e952fcd842cdaeaeb0b1de067bea37e90ab7cda9215617c4deb9299b

Contents?: true

Size: 1.92 KB

Versions: 2

Compression:

Stored size: 1.92 KB

Contents

require 'dm-aggregates'
module Ixtlan
  module ConditionalGet

    private

    def _conditional_get( method, id, modified_since, attribute )
      if self.count( attribute => modified_since,
                     :id => id ) == 0
        self.send( method, id )
      else
        # return false when up-to-date
        # that helps to distinguish nil from not-found
        false
      end
    end

    public

    def conditional_get!( id, modified_since, attribute = :updated_at )
      _conditional_get( :get!, id, modified_since, attribute )
    end

    def conditional_get( id, modified_since, attribute = :updated_at )
      _conditional_get( :get, id, modified_since, attribute )
    end
  end
  DataMapper::Associations::OneToMany::Collection.send( :include,
                                                        ConditionalGet )
  DataMapper::Associations::ManyToMany::Collection.send( :include,
                                                        ConditionalGet )

  module Immutable
    def self.included( model )
      model.class_eval do
        validates_with_method :validate_immutable
      end
    end
    def validate_immutable
      if dirty? && ! new?
        [ false, 'object is immutable' ]
      else
        true
      end
    end
  end

  module ModifiedBy

    def current_user=( user )
      @_current_user = user
    end

    def current_user
      @_current_user
    end

    def _modified_by
      self.modified_by = @_current_user if dirty? && @_current_user
    end

    def validate_modified_by
      if @_current_user || ! dirty?
        true
      else
        [ false, 'current_user was not set' ]
      end
    end

    module Methods
      def modified_by( *args )
        belongs_to :modified_by, *args

        before :valid?, :_modified_by

        validates_with_method :validate_modified_by
      end
    end

    DataMapper::Model.append_inclusions self
    DataMapper::Model.append_extensions Methods
  end
end

Version data entries

2 entries across 1 versions & 1 rubygems

Version Path
ixtlan-datamapper-0.1.0 lib/ixtlan/datamapper/immutable.rb~
ixtlan-datamapper-0.1.0 lib/ixtlan/datamapper/modified.rb~