<% require 'delegate' # Template for generate documents by Pandoc class MarkupNode < SimpleDelegator def title s = super s = ".#{id.split(/\./).last}" if s.empty? "#{'#' * nesting_level} #{s} {##{url(id)}}" end def meta return '' if nesting_level == 0 return '' if super[:skip_meta] hsh = {id: id}.merge(super) hsh.delete(:order_index) hsh.delete(:filename) hsh.delete(:parent) [].tap{|ary| ary << "Attribute | Value" ary << "--------- | -----" hsh.each{|k,v| ary << "#{k} | #{v}"} }.join("\n") end def body # links replacement txt = String.new(super) links.each{|l| txt.gsub! "[[#{l}]]", link(l)} # macro substitution macro.each{|m| txt.gsub! m.regex, m.substitution} txt end def link(ref) node = root.find{|n| n.id == ref} return "[#{ref}](#unknown)" unless node "[#{node.title}](##{url(ref)})" end def url(id) r = id.start_with?(/[[:digit:]]/) ? "p#{id}" : id r.downcase .gsub(/[^A-Za-z0-9]{1,}/, '-') .gsub(/^-/, '') .gsub(/-$/, '') end class Macro attr_reader :regex def initialize(regex, &substitution) @regex, @substitution = regex, substitution end def substitution @substitution.call() end end def macro [].tap do |ary| ary << Macro.new(/{{@@skip[\s\S]*?}}/, &Proc.new{ '' }) ary << Macro.new("{{@@list}}", &Proc.new{list}) ary << Macro.new("{{@@tree}}", &Proc.new{tree}) end end def tree this_level = nesting_level + 1 to_a.drop(1).inject([]) do |ary, n| lead_spaces = ' ' * (n.nesting_level - this_level) ary << "#{lead_spaces}* [#{n.title}](##{url(n.id)})" end.join("\n") end def list items.inject([]) do |ary, n| ary << "* [#{n.title}](##{url(n.id)})" end.join("\n") end end -%> % <%= @object.title %> % generated by Clerq on <%= Time.now.strftime('%B %e, %Y at %H:%M') %> % pandoc template <% for @node in @object.to_a.drop(1) -%> <% n = MarkupNode.new(@node) -%> <%= [n.title, n.meta, n.body].select{|t| !t.empty?}.join("\n\n") %> <% end %>