module Ruhoh::Parse

Constants

TopJSONregex
TopYAMLregex

Public Class Methods

data_file(*args) click to toggle source
# File lib/ruhoh/parse.rb, line 44
def self.data_file(*args)
  filepath = File.__send__(:join, args)
  if File.extname(filepath).to_s.empty?
    path = nil
    ["#{ filepath }.json", "#{ filepath }.yml", "#{ filepath }.yaml"].each do |result|
      filepath = path = result and break if File.exist?(result)
    end

    return nil unless path
  end

  file = File.open(filepath, 'r:UTF-8') { |f| f.read }

  File.extname(filepath) == ".json" ? json(file) : yaml(file)
end
json(file) click to toggle source
# File lib/ruhoh/parse.rb, line 67
def self.json(file)
  JSON.load(file) || {}
end
json_for_pages(front_matter, filepath) click to toggle source
# File lib/ruhoh/parse.rb, line 82
def self.json_for_pages(front_matter, filepath)
  return {} unless front_matter
  JSON.load(front_matter[0]) || {}
end
page_file(filepath) click to toggle source

Primary method to parse the file as a page-like object. File API is currently defines:

1. Top meta-data
2. Page Body

@returns[Hash Object] processed top meta-data, raw (unconverted) content body

# File lib/ruhoh/parse.rb, line 12
def self.page_file(filepath)
  result = {}
  front_matter = nil
  format = nil
  page = File.open(filepath, 'r:UTF-8') { |f| f.read }
  first_line = page.lines.first.to_s

  begin
    if (first_line.strip == '---')
      front_matter = page.match(TopYAMLregex)
      format = 'yaml'
   elsif (first_line.strip == '{')
      front_matter = page.match(TopJSONregex)
      format = 'json'
    end
  rescue => e
    raise "Error trying to read meta-data from #{ filepath }." +
    " Check your folder configuration.  Error details: #{e}"
  end

  if format == 'yaml'
    data = yaml_for_pages(front_matter, filepath)
    result["content"] = page.gsub(TopYAMLregex, '')
  else
    data = json_for_pages(front_matter, filepath)
    result["content"] = page.gsub(TopJSONregex, '')
  end

  result["data"] = data
  result
end
yaml(file) click to toggle source
# File lib/ruhoh/parse.rb, line 60
def self.yaml(file)
  YAML.load(file) || {}
rescue Psych::SyntaxError => e
  Ruhoh.log.error("ERROR in #{filepath}: #{e.message}")
  nil
end
yaml_for_pages(front_matter, filepath) click to toggle source
# File lib/ruhoh/parse.rb, line 71
def self.yaml_for_pages(front_matter, filepath)
  return {} unless front_matter
  YAML.load(front_matter[0].gsub(/---\n/, "")) || {}
rescue Psych::SyntaxError => e
  Ruhoh.log.error("Psych::SyntaxError while parsing top YAML Metadata in #{ filepath }\n" +
    "#{ e.message }\n" +
    "Try validating the YAML metadata using http://yamllint.com"
  )
  nil
end