Class: Preamble
- Inherits:
-
Object
- Object
- Preamble
- Defined in:
- lib/preamble.rb
Constant Summary collapse
- DEFAULTS =
{ external_encoding: Encoding.default_external }.freeze
Instance Attribute Summary collapse
-
#content ⇒ Object
Returns the value of attribute content.
-
#metadata ⇒ Object
Returns the value of attribute metadata.
Class Method Summary collapse
Instance Method Summary collapse
- #dump ⇒ Object
-
#initialize(metadata, content) ⇒ Preamble
constructor
A new instance of Preamble.
- #metadata_with_content ⇒ Object
- #save(path, options = {}) ⇒ Object
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
#content ⇒ Object
Returns the value of attribute content.
8 9 10 |
# File 'lib/preamble.rb', line 8 def content @content end |
#metadata ⇒ Object
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, = {}) f = open(path, "r:#{[: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) = paths.last.is_a?(Hash) ? paths.pop : {} paths.map { |path| Preamble.load(path, ) } 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
#dump ⇒ Object
19 20 21 |
# File 'lib/preamble.rb', line 19 def dump end |
#metadata_with_content ⇒ Object
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, = {}) = DEFAULTS.merge() open(path, "w:#{[:external_encoding]}") do |f| f.write end end |