我该怎么做:
class MyClass
tile 'some title'
collection do
node1 'node1'
node2 'node2'
another_collection do
node1 'node1'
node2 'node2'
end
end
end_node 'some text'
end
并产生以下内容:
MyClass.build #=>{:title=>'some title',:collection=>{:node1=>'node1',:node2=>'node2',:another_collection=>{:node1=>'node1',:node2=>'node2'}},:end_node=>'some text'}
我正在尝试制作简单的 DSL 并构建哈希树。我确信这可以通过 method_missing 和 instance_eval 来完成,但我现在不知道如何构建该逻辑。
感谢帮助
最佳答案
在您的method_missing
中,您应该检查是否给定了一个 block ,如果是,则递归调用它的主要方法:
class HashBuilder
def self.build &block
hb = HashBuilder.new
hb.instance_eval(&block)
hb.hash
end
attr_reader :hash
def initialize
@hash = {}
end
def method_missing meth, *args, &block
@hash[meth] = block ? HashBuilder.build(&block) : args.first
end
end
p HashBuilder.build{
a :b
c :d
e do
f :g
end
}
#=> {:a=>:b, :c=>:d, :e=>{:f=>:g}}
关于带 block 的 ruby 哈希树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6872596/