HTMLの変換
HParser::Parser#parseにはてな記法を渡すと、はてな記法が各要素に分解されます。
たとえば、
というふうに分解されます。
parser = HParser::Parser.new
parser.parse("hoge") # -> [#<HParser::Block::P>]parser.parse("*head") # -> [#<HParser::Block::Head>]parser.parse("*head\nfoo") # -> [#<HParser::Block::Head>,#<HParser::Block::P>]
あとは、HParser::Block::P#to_html
などのto_html
と名前の付いたメソッドを呼び出すことで、HTMLに変換することができます。
なので、HTMLの変換は次のようになります。
def to_html(input)
parser = HParser::Parser.new
node = parser.parse input.read
"<html><body>\n"+node.map{|x| x.to_html}.join("\n")+"\n</body></html>"
end
結果
最終的に次のようになります。
出力例:
#!/usr/local/bin/rubyrequire 'hparser'def to_html(input)
parser = HParser::Parser.new
node = parser.parse input.read
"<html><body>\n"+node.map{|x| x.to_html}.join("\n")+"\n</body></html>"
end
if ARGV.length == 0 then
puts to_html(STDIN)
else
open(ARGV[0]) do |io|
puts to_html(io)
end
end
$ cat sample.txt *Hello,world!! test - foo -- bar -- baz --- bar $ ruby make_hatena.rb sample.txt <html><body> <h1>Hello,world!!</h1> <p>test</p> <ul><li>foo</li><ul><li>bar</li><li>baz</li><ul><li>bar</li></ul></ul></ul> </body></html>