Sha256: 55aedde7dfd351b0a18b277772be95c116f6117d6795f945956f6524154f6c7d

Contents?: true

Size: 1.15 KB

Versions: 11

Compression:

Stored size: 1.15 KB

Contents

module Pupper
  module TrackableAttributes
    def self.included(base)
      base.send :include, ActiveModel::Dirty
      base.send :include, InstanceMethods

      class << base
        prepend ClassMethods
      end
    end

    module InstanceMethods
      def attributes
        @attributes ||= {}
      end

      def reload!
        restore_attributes
      end

      def rollback!
        restore_attributes
      end

      def refresh(**attrs)
        assign_attributes(**attrs)
        changes_applied
      end
    end

    module ClassMethods
      def _attributes
        @_attributes ||= []
      end

      def _attributes=(attrs)
        @_attributes = attrs
      end

      def attr_accessor(*attrs)
        # override the default so that we can hook into the created methods
        define_attribute_methods(*attrs)

        _attributes << attrs

        attrs.each do |attr|
          define_method attr do
            attributes[attr]
          end

          define_method "#{attr}=" do |value|
            send("#{attr}_will_change!") unless value == send(attr)
            attributes[attr] = value
          end
        end
      end
    end
  end
end

Version data entries

11 entries across 11 versions & 1 rubygems

Version Path
pupper-0.1.10 lib/pupper/trackable_attributes.rb
pupper-0.1.9 lib/pupper/trackable_attributes.rb
pupper-0.1.8 lib/pupper/trackable_attributes.rb
pupper-0.1.7 lib/pupper/trackable_attributes.rb
pupper-0.1.6 lib/pupper/trackable_attributes.rb
pupper-0.1.5 lib/pupper/trackable_attributes.rb
pupper-0.1.4 lib/pupper/trackable_attributes.rb
pupper-0.1.3 lib/pupper/trackable_attributes.rb
pupper-0.1.2 lib/pupper/trackable_attributes.rb
pupper-0.1.1 lib/pupper/trackable_attributes.rb
pupper-0.1.0 lib/pupper/trackable_attributes.rb