Created
January 20, 2012 18:41
-
-
Save sunaot/1648933 to your computer and use it in GitHub Desktop.
sample builder script in Ruby
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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