Module: Yarrow::Tools::FrontMatter

Defined in:
lib/yarrow/tools/front_matter.rb

Instance Method Summary collapse

Instance Method Details

#extract_split_content(text, options = {}) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/yarrow/tools/front_matter.rb', line 9

def extract_split_content(text, options={})
  pattern = /^(---\s*\n.*?\n?)^(---\s*$\n?)/m
  if text =~ pattern
    content = text.sub(pattern, "")

    begin
      if options.key?(:symbolize_keys)
        meta = symbolize_keys(YAML.load($1))
      else
        meta = YAML.load($1)
      end
      return [content, meta]
    rescue Psych::SyntaxError => error
      if defined? ::Logger
        # todo: application wide logger
        logger = ::Logger.new(STDOUT)
        logger.error "#{error.message}"
      end
      return [content, nil]
    end
  end

  [text, nil]
end

#read_split_content(path, options = {}) ⇒ Object



5
6
7
# File 'lib/yarrow/tools/front_matter.rb', line 5

def read_split_content(path, options={})
  extract_split_content(File.read(path, :encoding => 'utf-8'), options)
end

#symbolize_keys(hash) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/yarrow/tools/front_matter.rb', line 34

def symbolize_keys(hash)
  hash.inject({}) do |result, (key, value)|
    new_key = case key
              when String then key.to_sym
              else key
              end
    new_value = case value
                when Hash then symbolize_keys(value)
                when Array then value.map { |entry| symbolize_keys(entry) }
                else value
                end
    result[new_key] = new_value
    result
  end
end