哈希不能合并

时间:2019-12-19 11:38:43

标签: ruby hash merge dsl

我对合并方法有疑问。 目前,我正在使用DSL模型,并且需要创建父函数。 我想合并散列,但是在尝试执行此操作时出现错误。 问题是当我有2个散列而不是2个数组时为什么会出现此错误。 感谢您的帮助!

init.rb文件:

require "./configus"
require "pry"

config = Configus.config :staging, :production do
  production do
    key1 "value1"
    key2 "value2"
    group1 do
      key3 "value3"
      key4 "value4"
    end
  end

  staging do
    key2 "new value2"
    group1 do
      key4 "new value4"
    end
  end

  development do
    key1 "new value1"
    key2 "value2"
    group1 do
      key3 "new value3"
      key4 "value4"
    end
  end

  productionisgsgsd do
    key10 "value10"
  end
end

puts config

配置文件(已更新):

class Configus
  class InHash
    attr_reader :inner_hash

    def initialize
      @inner_hash = {}
    end

    def method_missing(name, *args, &block)
      if block_given?
        context = InHash.new
        context.instance_eval &block
        result = context.inner_hash
      else
        result = args
      end

      @inner_hash[name] = result
    end
  end

  def self.config(environment, parent = nil, &block)
    in_hash = InHash.new
    in_hash.instance_eval &block
    in_hash.inner_hash
    temp = in_hash.inner_hash.keys
    index = temp.find_index(environment)

    p in_hash.inner_hash[parent]
    p in_hash.inner_hash[environment]

    if parent && environment != nil
      in_hash.inner_hash[environment].deep_merge(in_hash.inner_hash[parent])
    elsif environment == temp[index]
      in_hash.inner_hash[environment]
    end
  end
end

合并有效,但不正确。

我签出了deep_merge方法,但是它也不起作用:/ 输出:

undefined method `deep_merge' for #<Hash:0x0000562296df8d38> (NoMethodError)

0 个答案:

没有答案