Class: FrontMatter

Inherits:
Object
  • Object
show all
Defined in:
lib/front_matter.rb

Constant Summary collapse

VERSION =
'1.2.1'

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(opts = {}) ⇒ FrontMatter

Returns a new instance of FrontMatter.



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/front_matter.rb', line 20

def initialize( opts={} )
  comment_marker   = %r{(?<comment> ^\s* \W{1,2} )}x
  @setting = {
    :patterns => {
      :header => {
        :filetype => %r{.*},
        :pattern  => %r{
          (?<start> #{comment_marker} \s* [-=#*]{3,} .* )[\r\n]
          (?<content> (?: \k<comment> .* [\r\n])+)
          \k<start>
          }x
      },
      :yaml => {
        :filetype => %r{.*},
        :pattern  => %r{
          (?<start> #{comment_marker} \s* -{3} )[\r\n]
          (?<content> (?: \k<comment> .* [\r\n])+)
          (?<empty>^ \s* $)
          }x
      },
    },
    :unindent   => false ,
    :as_yaml    => false ,
  }
  @setting.merge!(opts)
end

Instance Attribute Details

#settingObject

Returns the value of attribute setting.



19
20
21
# File 'lib/front_matter.rb', line 19

def setting
  @setting
end

Instance Method Details

#extract(contents, filetype = []) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/front_matter.rb', line 47

def extract(contents, filetype=[])
  unless filetype.empty?
    patterns = @setting[:patterns].select { |kind, pattern|
      filetype.any { |ft| pattern[:filetype].match(ft)}
    }
  else
    patterns = @setting[:patterns]
  end

  union_patterns = Regexp.union(patterns.collect{ |k, p| p[:pattern] })
  results = [] 
  contents.mscan(union_patterns).each { |m| 
    results << m[:content].gsub(/^#{Regexp.escape(m[:comment])}/, "") 
  }
  
  results.map! { |r| r.unindent } if @setting[:unindent]
  results.map! { |r| "---\n#{r}" } if @setting[:as_yaml]

  return results
end

#extract_file(path, opts = {}) ⇒ Object



68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/front_matter.rb', line 68

def extract_file(path, opts={})

  filetype = opts[:filetype] ? opts[:filetype] : []
  if opts[:firstline] || opts[:lastline]
    firstline = opts[:firstline] ? opts[:firstline] - 1 : 0
    lastline = opts[:lastline] ? opts[:lastline] -1 : -1
    return extract(File.readlines(path)[firstline..lastline].join, filetype)
  else
    return extract(File.read(path), filetype)
  end

end