Sha256: a14139452a8551d76ee2b7ef2ce0c726abd138af6879e3f51c1b425ff2dd15ce

Contents?: true

Size: 1.22 KB

Versions: 5

Compression:

Stored size: 1.22 KB

Contents

module RspecApiDocs
  class Resource
    class Example
      class DeepHashSet
        attr_reader :hash, :keys, :value, :node

        def self.call(*args)
          new(*args).call
        end

        def initialize(hash, keys, value)
          @hash = hash
          @keys = keys
          @value = value
          @node = []
        end

        def call
          keys.each_with_index do |key, index|
            case
            when key.nil?
              deep_set_value_at_array(index)
              break
            when index == keys.size - 1
              set_value_at(key)
            else
              node << key
            end
          end

          hash
        end

        private

        attr_reader :node

        def deep_set_value_at_array(index)
          array = deep_find(hash, node)
          array && array.each do |inner_hash|
            DeepHashSet.call(inner_hash, keys[index+1..-1], value)
          end
        end

        def set_value_at(key)
          part = deep_find(hash, node)
          if part.is_a?(Hash) && !part[key].nil?
            part[key] = value
          end
        end

        def deep_find(hash, keys)
          keys.inject(hash) { |h, k| h && h[k] }
        end
      end
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
rspec-api-docs-1.1.0 lib/rspec_api_docs/formatter/resource/example/deep_hash_set.rb
rspec-api-docs-1.0.0 lib/rspec_api_docs/formatter/resource/example/deep_hash_set.rb
rspec-api-docs-0.14.0 lib/rspec_api_docs/formatter/resource/example/deep_hash_set.rb
rspec-api-docs-0.13.0 lib/rspec_api_docs/formatter/resource/example/deep_hash_set.rb
rspec-api-docs-0.12.0 lib/rspec_api_docs/formatter/resource/example/deep_hash_set.rb