Skip to content

Instantly share code, notes, and snippets.

@sunaot
Created January 20, 2012 18:41
Show Gist options
  • Save sunaot/1648933 to your computer and use it in GitHub Desktop.
Save sunaot/1648933 to your computer and use it in GitHub Desktop.
sample builder script in Ruby
module Builder
def self.method_missing name, *args, &block
tag = Tag.new
tag.send(name, *args, &block).flatten.join
end
class Tag
def initialize
@tags = []
end
def method_missing *args, &block
name = args.shift
if block
child = Tag.new
child.instance_eval(&block)
block_value = tagify(name, child.valuate)
@tags << block_value
block_value
else
value = args.shift
@tags << {:name => name, :value => value}
end
end
def valuate
@tags.map do |tag|
tag.kind_of?(Hash) ?
tagify(tag[:name], tag[:value]) :
tag
end
end
def tagify name, value
["<#{name}>", value, "</#{name}>"]
end
end
end
require 'expectations'
Sample = <<TREE.gsub(/\s/, '')
<root>
<book>
<title>souseki1</title>
<author>souseki</author>
</book>
<book>
<title>souseki2</title>
<author>souseki</author>
</book>
<book>
<title>souseki3</title>
<author>souseki</author>
</book>
</root>
TREE
Expectations do
expect Sample do
titles = %w[ souseki1 souseki2 souseki3 ]
Builder.root do
titles.each do |t|
book do
title t
author "souseki"
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment