public
Last active

Ruby DSL - HTML生成

  • Download Gist
html-builder.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
#!/usr/bin/ruby
#[=c= ruby -rubygems % ]
 
class HTMLBuilder
def initialize (tag_name = 'html', indent = 0, &block)
@indent = indent
@tag_name = tag_name
@attrs = {}
@contents = []
self.instance_eval(&block)
end
 
def method_missing (name, *args, &block)
if block
@contents << HTMLBuilder.build(name, @indent + 1, &block)
else
@attrs[name] = args.join
end
end
 
def text (value)
@contents << value
end
 
def self.build (*args, &block)
builder = self.new(*args, &block)
builder.meoooooooooooooooow
end
 
def self.tag (name, attrs, empty = false)
end
 
def meoooooooooooooooow
attrs =
if @attrs.empty?
""
else
@attrs.map {|k, v| %Q<#{k}="#{v}"> } .join(" ")
end
tag = "#{' ' * @indent}<#{@tag_name}#{" " unless attrs.empty?}#{attrs}#{" /" if @contents.empty?}>"
return tag if @contents.empty?
indent = ' ' * @indent
return <<-"EOM".chomp
#{tag}
#{@contents.join("\n")}
#{indent}</#{@tag_name}>
EOM
end
end
 
 
html = HTMLBuilder.build {
body {
p {
text "hoge"
}
a {
href "http://snca.net"
target "_blank"
text "宇宙忍者猫団"
}
hr {}
ul {
2.times do |t|
li {
text t
}
end
}
}
}
 
 
puts html
 
=begin Result
<html>
<body>
<a href="http://snca.net">
宇宙忍者猫団
</a>
<hr />
<ul>
<li>
0
</li>
<li>
1
</li>
</ul>
</body>
</html>
=end

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.