Sha256: f03a06b30fb26ba4500a96afcfae42da8b381e73cea176f1054a05107b6f7e1c

Contents?: true

Size: 1.67 KB

Versions: 16

Compression:

Stored size: 1.67 KB

Contents

require 'virtus'
require 'active_support/concern'
require 'active_model'

module TrackerApi
  module Resources
    module Base
      extend ActiveSupport::Concern

      include ActiveModel::Model
      include ActiveModel::Dirty

      included do
        include Virtus.model
        include OverrideAttributes

        attribute :id, Integer

        def initialize(attrs)
          super

          # always reset dirty tracking on initialize
          clear_changes_information
        end

        private

        # @return [Hash] key value pairs for just the changed attributes with their new values.
        def just_changes
          # @see changes in ActiveModel::Dirty in active_model/dirty.rb
          #     { attr => [original value, new value] }
          changes.inject({}) do |h, (k, v)|
            h[k] = v[1]; h;
          end
        end
      end

      module OverrideAttributes
        extend ActiveSupport::Concern

        module ClassMethods
          def attribute(name, type, options = {})
            define_attribute_methods name

            attribute = super
            create_writer_with_dirty_tracking(name)
            attribute
          end

          private

          def create_writer_with_dirty_tracking(name)
            method_str = <<-RUBY
              def #{name}=(value)
                prev_value = #{name}
                new_value  = value
                if prev_value != new_value
                  #{name}_will_change!
                  new_value = super(value)
                end
                new_value
              end
            RUBY

            class_eval method_str, __FILE__, __LINE__ + 1
          end
        end
      end
    end
  end
end

Version data entries

16 entries across 16 versions & 1 rubygems

Version Path
v2gpti-1.3.5 tracker_api/lib/tracker_api/resources/base.rb
v2gpti-1.3.4 tracker_api/lib/tracker_api/resources/base.rb
v2gpti-1.3.3 tracker_api/lib/tracker_api/resources/base.rb
v2gpti-1.3.2 tracker_api/lib/tracker_api/resources/base.rb
v2gpti-1.3.1 tracker_api/lib/tracker_api/resources/base.rb
v2gpti-1.3.0 tracker_api/lib/tracker_api/resources/base.rb
v2gpti-1.2.9 tracker_api/lib/tracker_api/resources/base.rb
v2gpti-1.2.8 tracker_api/lib/tracker_api/resources/base.rb
v2gpti-1.2.7 tracker_api/lib/tracker_api/resources/base.rb
v2gpti-1.2.6 tracker_api/lib/tracker_api/resources/base.rb
v2gpti-1.2.5 tracker_api/lib/tracker_api/resources/base.rb
v2gpti-1.2.4 tracker_api/lib/tracker_api/resources/base.rb
v2gpti-1.2.3 tracker_api/lib/tracker_api/resources/base.rb
v2gpti-1.2.2 tracker_api/lib/tracker_api/resources/base.rb
v2gpti-1.2.1 tracker_api/lib/tracker_api/resources/base.rb
v2gpti-1.2.0 tracker_api/lib/tracker_api/resources/base.rb