class Forematter::Frontmatter

Attributes

data[R]

Public Class Methods

new(input) click to toggle source
# File lib/forematter/frontmatter.rb, line 5
def initialize(input)
  init_stream(input)
end

Public Instance Methods

[](key) click to toggle source
# File lib/forematter/frontmatter.rb, line 19
def [](key)
  data.children.each_index do |i|
    next unless i % 2
    return data.children[i + 1] if data.children[i].to_ruby == key
  end
  nil
end
[]=(key, val) click to toggle source
# File lib/forematter/frontmatter.rb, line 27
def []=(key, val)
  data.children.each_index do |i|
    next unless i % 2
    if data.children[i].to_ruby == key
      data.children[i + 1] = thunk(val, data.children[i + 1])
      return
    end
  end

  data.children << Psych::Nodes::Scalar.new(key)
  data.children << thunk(val)
end
delete(key) click to toggle source
# File lib/forematter/frontmatter.rb, line 40
def delete(key)
  data.children.each_index do |i|
    next unless i % 2
    if data.children[i].to_ruby == key
      val = data.children.delete_at(i + 1)
      data.children.delete_at(i)
      return val
    end
  end
end
has_key?(key)
Alias for: key?
key?(key) click to toggle source
# File lib/forematter/frontmatter.rb, line 9
def key?(key)
  data.children.each_index do |i|
    next unless i % 2
    return true if data.children[i].to_ruby == key
  end

  false
end
Also aliased as: has_key?
rename(key, new_key) click to toggle source
# File lib/forematter/frontmatter.rb, line 51
def rename(key, new_key)
  data.children.each_index do |i|
    next unless i % 2
    if data.children[i].to_ruby == key
      data.children[i].value = new_key
      return
    end
  end
end
to_yaml() click to toggle source
# File lib/forematter/frontmatter.rb, line 61
def to_yaml
  @stream.to_yaml
end

Protected Instance Methods

init_stream(input) click to toggle source
# File lib/forematter/frontmatter.rb, line 83
def init_stream(input)
  doc = YAML.parse_stream(input).children.first
  @data = doc.children.first
  @stream = YAML.parse_stream('')
  @stream.children << doc
end
parse_yaml(val) click to toggle source
# File lib/forematter/frontmatter.rb, line 77
def parse_yaml(val)
  YAML.parse(YAML.dump(val)).children.first
end
thunk(val, old = nil) click to toggle source
# File lib/forematter/frontmatter.rb, line 67
def thunk(val, old = nil)
  return val if val.is_a?(Psych::Nodes::Node)
  val = parse_yaml(val)
  if old.is_a?(Psych::Nodes::Sequence) && val.is_a?(Psych::Nodes::Sequence)
    old.children.replace(val.children)
    val = old
  end
  val
end