おそらく箱から外に出ないかもしれませんが、redcarpetを使用すると、カスタムレンダラーを作成してツリーを構築し、それを操作することができます。
この場合、MarkdownおよびRendererインスタンスを再利用することはできませんが、カスタムレンダラーサブクラスのすべてのメソッドは文字列を返すことになっています。このようなものが出発点になる可能性があります。
class StackRenderer < Redcarpet::Render::Base
attr_reader :items
def initialize
super
@items = []
end
def header(title, level)
items << { :text => title, :level => level, :type => :header }
"#{'#' * level} #{title}\n\n"
end
def paragraph(text)
items << { :text => text, :type => :paragraph }
"#{text}\n\n"
end
end
# example...
sr = StackRenderer.new
md = Redcarpet::Markdown.new(sr)
text = <<-EOF
# This is a title
And a short paragraph...
EOF
md.render(text) # => "# This is a title\n\nAnd a short paragraph...\n\n"
sr.items # => [{:type=>:header, :level=>1, :text=>"This is a title"},
# {:type=>:paragraph, :text=>"And a short paragraph..."}]
出典
2012-03-15 16:02:38
lwe