开发者

ruby hash tree with blocks

开发者 https://www.devze.com 2023-03-23 23:53 出处:网络
how can I do this: class MyClass tile \'some title\' collection do node1 \'node1\' node2 \'node2\' another_collection do

how can I do this:

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

and produce following:

MyClass.build #=>{:title=>'some title',:collection=>{:node1=>'node1',:node2=>'node2',:another_collection=>{:开发者_如何学Gonode1=>'node1',:node2=>'node2'}},:end_node=>'some text'}

What i was trying is to make simple DSL and build hash tree. I'm sure that can be done with method_missing and instance_eval, but i don't now how to build that logic.

Thanks for help


In your method_missing, you should check if a block is given, and, if so, recursively call the main method with it:

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}}
0

精彩评论

暂无评论...
验证码 换一张
取 消