我有简单的DSL,我从rails中添加了deep_merge gem,以合并包含其他哈希(:production => { :key1 =>["value1"],:group1 => { :key2 =>["value2"] } }
)的哈希。
但是当我想输出合并键的值时,ruby输出nil。
Configus.rb:
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
@inner_hash[name] = context
elsif args.empty?
@inner_hash[name]
else
@inner_hash[name] = args
end
end
end
def self.config(environment,parent = nil,&block)
in_hash = InHash.new
in_hash.instance_eval &block
keys = in_hash.inner_hash.keys
index = keys.find_index(environment)
if parent && environment
parent_hash = in_hash.inner_hash[parent]
adopted_hash = in_hash.inner_hash[environment]
merged_hash = parent_hash.deep_merge!(adopted_hash)
in_hash
elsif environment == keys[index]
in_hash.inner_hash[environment]
end
end
end
Init.rb:
require "./configus"
require "pry"
#Binding.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
end
puts config.key1
没有父母的情况下撬出输出(例如::staging = adopted_hash,:production = parent_hash
):
=> #<Configus::InHash:0x000056372547fd30
@inner_hash=
{:key1=>["value1"],:key2=>["value2"],:group1=>
#<Configus::InHash:0x000056372547fbc8
@inner_hash={:key3=>["value3"],:key4=>["value4"]}>}>
在育儿环境下撬动:
=> #<Configus::InHash:0x0000557f88a5f5e8
@inner_hash=
{:production=>
#<Configus::InHash:0x0000557f88a5f1b0
@inner_hash=
{:key1=>["value1"],:group1=>#<Configus::InHash:0x0000557f88a5ed50 @inner_hash={:key3=>["value3"],:key4=>["value4"]}>,:deep_merge!=>
[#<Configus::InHash:0x0000557f88a5ea08
@inner_hash={:key2=>["new value2"],:group1=>#<Configus::InHash:0x0000557f88a5e5f8 @inner_hash={:key4=>["new value4"]}>}>]}>,:staging=>
#<Configus::InHash:0x0000557f88a5ea08
@inner_hash={:key2=>["new value2"],:group1=>#<Configus::InHash:0x0000557f88a5e5f8 @inner_hash={:key4=>["new value4"]}>}>}>