Sha256: 084d72b6008c4bc948115e5ab2e0de99e27ea03d3f344dd84104bf9bec148fd3

Contents?: true

Size: 1.9 KB

Versions: 6

Compression:

Stored size: 1.9 KB

Contents

module Lotus
  module Entity
    # Dirty tracking for entities
    #
    # @since 0.3.1
    #
    # @example Dirty tracking
    #   require 'lotus/model'
    #
    #   class User
    #     include Lotus::Entity
    #     include Lotus::Entity::DirtyTracking
    #
    #     attributes :name
    #   end
    #
    #   article = Article.new(title: 'Generation P')
    #   article.changed? # => false
    #
    #   article.title = 'Master and Margarita'
    #   article.changed? # => true
    #
    #   article.changed_attributes # => {:title => "Generation P"}
    module DirtyTracking
      # Override initialize process.
      #
      # @param attributes [Hash] a set of attribute names and values
      #
      # @since 0.3.1
      #
      # @see Lotus::Entity#initialize
      def initialize(attributes = {})
        super
        @_initial_state = Utils::Hash.new(to_h).deep_dup
      end

      # Getter for hash of changed attributes.
      # Return empty hash, if there is no changes
      # Getter for hash of changed attributes. Value in it is the previous one.
      #
      # @return [::Hash] the changed attributes
      #
      # @since 0.3.1
      #
      # @example
      #   require 'lotus/model'
      #
      #   class Article
      #     include Lotus::Entity
      #     include Lotus::Entity::DirtyTracking
      #
      #     attributes :title
      #   end
      #
      #   article = Article.new(title: 'The crime and punishment')
      #   article.changed_attributes # => {}
      #
      #   article.title = 'Master and Margarita'
      #   article.changed_attributes # => {:title => "The crime and punishment"}
      def changed_attributes
        Hash[@_initial_state.to_a - to_h.to_a]
      end

      # Checks if the attributes were changed
      #
      # @return [TrueClass, FalseClass] the result of the check
      #
      # @since 0.3.1
      def changed?
        changed_attributes.any?
      end
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
lotus-model-0.5.2 lib/lotus/entity/dirty_tracking.rb
lotus-model-0.5.1 lib/lotus/entity/dirty_tracking.rb
lotus-model-0.5.0 lib/lotus/entity/dirty_tracking.rb
lotus-model-0.4.1 lib/lotus/entity/dirty_tracking.rb
lotus-model-0.4.0 lib/lotus/entity/dirty_tracking.rb
lotus-model-0.3.2 lib/lotus/entity/dirty_tracking.rb