Sha256: 9154e1889d25e3b248deb857e90cee5e6dcec7ea6f79565535d1cbe7651c7cfb

Contents?: true

Size: 1.42 KB

Versions: 6

Compression:

Stored size: 1.42 KB

Contents

require 'valise/strategies/set'

module Valise
  module Strategies
    class MergeDiff < Set
      def initialize(options)
        @stack = options[:stack]
      end

      class TopMost < MergeDiff
        register :topmost
        default

        def merge(item)
          item.load_contents
        end

        def diff(item, value)
          value
        end
      end

      class HashMerge < MergeDiff
        register :hash_merge

        def merge(item)
          merge_stack(@stack.not_above(item).reverse)
        end

        def merge_stack(stack)
          stack.present.inject({}) do |hash, item|
            deep_merge(hash, item.load_contents)
          end
        end

        def deep_merge(collect, item)
          item.each_pair do |key, value|
            case value
            when Hash
              collect[key] ||= {}
              deep_merge(collect[key], value)
            else
              collect[key] = value
            end
          end
          collect
        end

        def diff(item, new_contents)
          diff_with = merge_stack(@stack.below(item).reverse)
          result = new_contents.dup

          diff_with.each_pair do |key, value|
            if result.has_key?(key)
              if result[key] == value
                result.delete(key)
              end
            else
              result[key] = nil
            end
          end

          result
        end
      end
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
valise-1.1.2 lib/valise/strategies/merge-diff.rb
valise-1.1.1 lib/valise/strategies/merge-diff.rb
valise-1.1.0 lib/valise/strategies/merge-diff.rb
valise-1.0.0 lib/valise/strategies/merge-diff.rb
valise-0.9.1 lib/valise/strategies/merge-diff.rb
valise-0.9.0 lib/valise/strategies/merge-diff.rb