I am trying to create a 'foo' item with a child item called 'bar'. The expected output is:
foo_item = Item @name="foo", @children=[<...>]
foo_item children = [Item @name="bar", @children=[]]
I am using blocks, binding and eval. This is my code:
class Item
attr_accessor :name, :children
def initialize name
@name = name
@children = []
end
end
def item(item_name)
@item = Item.new(item_name)
if @context
@context.eval('@item.children') << @item
end
if block_given?
old_context = @context if @context
@context = binding
yield
if old_context
@context = old_context
else
@context = nil
end
end
@item
end
foo_item = item('foo') do
item('bar')
end
puts "foo_item = #{foo_item.inspect}"
puts "foo_item children = #{foo_item.children.inspect}"
In the actual output below, the foo_item
contains the bar
item, whose child is also the bar
item:
foo_item = Item @name="bar", @children=[<...>]
foo_item children = [Item @name="bar", @children=[<...>]]
Given the same input:
foo_item = item('foo') do
item('bar')
end
How do I get the expected output above?