Class: Preamble

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

Constant Summary collapse

DEFAULTS =
{
  external_encoding: Encoding.default_external
}.freeze

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(metadata, content) ⇒ Preamble

Returns a new instance of Preamble.



10
11
12
13
# File 'lib/preamble.rb', line 10

def initialize(, content)
  @metadata = 
  @content = content
end

Instance Attribute Details

#contentObject

Returns the value of attribute content.



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

def content
  @content
end

#metadataObject

Returns the value of attribute metadata.



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

def 
  @metadata
end

Class Method Details

.load(path, options = {}) ⇒ Object



78
79
80
81
# File 'lib/preamble.rb', line 78

def self.load(path, options = {})
  f = open(path, "r:#{options[:external_encoding]}")
  parse(f.read)
end

.load_multiple(*paths) ⇒ Object



83
84
85
86
# File 'lib/preamble.rb', line 83

def self.load_multiple(*paths)
  options = paths.last.is_a?(Hash) ? paths.pop : {}
  paths.map { |path| Preamble.load(path, options) }
end

.parse(data) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/preamble.rb', line 31

def self.parse(data)
  preamble_lines = +""
  content_lines = +""

  state = :before_preamble

  f = StringIO.new(data)
  f.each do |line|
    stripped = line.strip

    case state
    when :before_preamble

      new_state = case stripped
      when "---"
        :preamble
      when ""
        :before_preamble
      else
        content_lines << line
        :after_preamble
      end

    when :preamble

      new_state = case stripped
      when "---"
        :after_preamble
      else
        preamble_lines << line
        :preamble
      end

    when :after_preamble
      new_state = :after_preamble
      content_lines << line

    else
      raise "Invalid State: #{state}"
    end

    state = new_state
  end

  new(YAML.safe_load(preamble_lines), content_lines)
end

Instance Method Details

#dumpObject



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

def dump
  
end

#metadata_with_contentObject



15
16
17
# File 'lib/preamble.rb', line 15

def 
  "#{@metadata.to_yaml}---\n#{@content}"
end

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



23
24
25
26
27
28
29
# File 'lib/preamble.rb', line 23

def save(path, options = {})
  options = DEFAULTS.merge(options)

  open(path, "w:#{options[:external_encoding]}") do |f|
    f.write 
  end
end