Sha256: 52ab5aea264edff5b8995fefacaa7c82d32986135e46edbf6f832fda72324cd8

Contents?: true

Size: 1.61 KB

Versions: 1

Compression:

Stored size: 1.61 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

        def complex?
          raise NoMethodError, "expected #{self.class} to implement #complex?"
        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

1 entries across 1 versions & 1 rubygems

Version Path
hash_deep_diff-0.3.2 lib/hash_deep_diff/delta/acts_as_delta.rb