Sha256: 2e3094841697d37c9d874c9f8c2e4f4b091e0f5db084fcdc10567baf3643cc2a

Contents?: true

Size: 1.5 KB

Versions: 2

Compression:

Stored size: 1.5 KB

Contents

# frozen_string_literal: true

require 'forwardable'

module HashDeepDiff
  module Delta
    # This module includes behavior that is needed to use deltas instead of Hash inside this gem
    module ActsAsDelta
      def self.included(base)
        base.prepend(Initialize)
        base.include(InstanceMethods)
        base.extend(Forwardable)
        base.def_delegators :@delta, :==, :each_with_object, :each_key, :[],
                            :to_a, :empty?, :keys
      end

      # Assumes that the class will include method delta that will return a representation of an
      # instance of a class as a Hash
      module InstanceMethods
        # TOFIX poor naming
        def diff_prefix
          path.map { |key| "[#{key}]" }.join
        end

        # TOFIX poor naming
        def path
          @prefix + [@delta.keys.first]
        end

        def to_h
          @delta
        end

        def to_hash
          @delta
        end

        def to_s
          to_str
        end

        def to_str
          raise NoMethodError, "expected #{self.class} to implement #to_str"
        end
      end

      # Override #initialize method
      module Initialize
        def initialize(path:, value:)
          # TOFIX this may prohibit usage of hashes with Array keys
          if path.respond_to?(:to_ary)
            @delta = { path[-1] => value }
            @prefix = path[0..-2]
          else
            @delta = { path => value }
            @prefix = []
          end
        end
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
hash_deep_diff-0.3.1 lib/hash_deep_diff/delta/acts_as_delta.rb
hash_deep_diff-0.3.0 lib/hash_deep_diff/delta/acts_as_delta.rb