您可以编写一个小的自定义 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>
那是你要找的吗?