Class: Lookbook::KeyValueTagParser

Inherits:
Service
  • Object
show all
Defined in:
lib/lookbook/services/tags/key_value_tag_parser.rb

Constant Summary collapse

KEY_VALUE_REGEX =
/^([^\s]+)\s+(.+)$/

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods inherited from Service

call

Constructor Details

#initialize(text) ⇒ KeyValueTagParser

Returns a new instance of KeyValueTagParser.



7
8
9
# File 'lib/lookbook/services/tags/key_value_tag_parser.rb', line 7

def initialize(text)
  @text = text.to_s
end

Instance Attribute Details

#textObject (readonly)



5
6
7
# File 'lib/lookbook/services/tags/key_value_tag_parser.rb', line 5

def text
  @text
end

Instance Method Details

#callObject

Raises:



11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/lookbook/services/tags/key_value_tag_parser.rb', line 11

def call
  text.strip.match(KEY_VALUE_REGEX) do |matches|
    key = matches[1]
    value = begin
      YAML.safe_load(matches[2] || "~")
    rescue ::Psych::SyntaxError => exception
      raise ParserError.new("Invalid YAML in tag text '#{@text}'", scope: "key_value_tag.parser", original: exception)
    end
    return [key, value]
  end
  raise ParserError.new("Could not parse key:value pair from '#{@text}'", scope: "key_value_tag.parser")
end