Class: SatanicPages::Frontmatter

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

Defined Under Namespace

Classes: MissingAttributeError

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(hash) ⇒ Frontmatter

Returns a new instance of Frontmatter.



8
9
10
# File 'lib/satanic_pages/frontmatter.rb', line 8

def initialize(hash)
  @hash = (hash&.with_indifferent_access || {}).freeze
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, *args) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/satanic_pages/frontmatter.rb', line 16

def method_missing(name, *args)
  if name.to_s.end_with?("!")
    attribute = name.to_s.chomp("!").to_sym

    unless @hash[attribute]
      raise MissingAttributeError, "Missing attribute: #{name.to_s.chomp("!")}"
    end

    @hash[attribute]

  elsif name.to_s.end_with?("?")
    @hash[name.to_s.chomp("?").to_sym].present?

  else
    @hash[name]
  end
end

Class Method Details

.parse(source) ⇒ Object



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

def self.parse(source)
  frontmatter = nil

  rest = source.gsub(/\A---\n(.*?)\n---\n/m) do
    begin
      frontmatter = YAML.safe_load($1)
      ""
    rescue => e
      Rails.logger.error("Error parsing frontmatter: #{e.message}")
      $&
    end
  end

  [new(frontmatter), rest]
end

Instance Method Details

#to_hObject



12
13
14
# File 'lib/satanic_pages/frontmatter.rb', line 12

def to_h
  @hash
end