require 'yaml' module Mdoc class Text attr_accessor :meta, :body, :title, :author, :date def initialize file @file = file fh = file.is_a?(String) ? ::File.new(file, 'r:utf-8') : file @raw_meta = Array.new @body = String.new first_line = true # if this is the first line meta_type = nil # three meta format supported on_meta = true # read lines on meta or on body # parse the file, load all into the object fh.each do |line| # ignore heading blank lines next if first_line and /^\s*$/.match(line) # parse first line, determine the meta format if first_line first_line = false if /\%\s*\-{3,}\s*$/ =~ line meta_type = :o # original format next # skip the first line elsif /\%\s*.+$/ =~ line meta_type = :p # pandoc format elsif /^[a-z]+\:\s*/ =~ line meta_type = :m # multi-key format else on_meta = false end end if on_meta # catch end of meta line if meta_type == :o and /\%\s*\-{3,}\s*$/ =~ line on_meta = false next # skip the elsif meta_type == :p on_meta = false unless /^\%/ =~ line elsif meta_type == :m and /^\s*$/ =~ line on_meta = false next end # puts line @raw_meta << line.gsub(/^\s*\%\s*/, '').chomp next end @body << line end # parse lines # set title, author and date if meta_type == :p @title = @raw_meta[0] || '' @author= @raw_meta[1] || '' @date = @raw_meta[2] || '' @meta = { 'title' => @title, 'author' => @author, 'date' => @date } else @meta = YAML.load(@raw_meta.join("\n")) if @meta @title = @meta['title'] || '' @author= @meta['author'] || '' @date = @meta['date'].to_s || '' end end end end end