小さなカスタムDSLを書くことができます(コードを改善して改善することができます):
大幅に改善できる小さなDSL:
class ReportHtmlMaker
def initialize(output)
@output = output
end
def content(text)
@output << text.to_s
nil
end
def translate_semantic_tag(tagname,attributes={})
newline = "" # "\r\n" uncomment to add newlines
case tagname.to_sym
when :group_header
tagname = "h1"
attributes[:id] = "report_group_header"
when :title
tagname = "h2"
attributes[:class] = "report_title"
when :description
tagname = "p"
end
@output << "<#{tagname}"
attributes.each { |attr,value| @output << " #{attr}='#{value}'" }
if block_given?
@output << ">" << newline
content = yield
if content
@output << content.to_s << newline
end
@output << "</#{tagname}>" << newline
else
@output << "/>" << newline
end
nil
end
alias method_missing translate_semantic_tag
def self.generate(output, &block)
ReportHtmlMaker.new(output).instance_eval(&block)
end
end
使用法:
output = String.new
ReportHtmlMaker.generate(output) do #or, use STDOUT to output to console
group_header do
title do
"Response Distribution"
end
description do
"lorem ipsum dolor mit"
end
end
end
出力:
puts output # =>
<div id='report_group_header'>
<h2 class='report_title'>Response Distribution</h2>
<p class='report_description'>lorem ipsum dolor mit</p>
</h1>
それはあなたが探していたものでしたか?