Module: FastComments::Jekyll::AttributeParser

Defined in:
lib/fastcomments/jekyll/attribute_parser.rb

Overview

Parses a Liquid tag’s markup (“k=v k=‘s’ k=page.x”) into a snake-keyed Hash.

Constant Summary collapse

TOKEN_RE =
/([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(?:"([^"]*)"|'([^']*)'|(\S+))/.freeze

Class Method Summary collapse

Class Method Details

.coerce(token, context) ⇒ Object

Unquoted values coerce to Integer/Float/Boolean/nil, else resolve as a Liquid context variable (e.g. page.slug). Unresolved variables become nil.



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/fastcomments/jekyll/attribute_parser.rb', line 29

def coerce(token, context)
  case token
  when /\A-?\d+\z/ then Integer(token, 10)
  when /\A-?\d*\.\d+\z/ then Float(token)
  when "true" then true
  when "false" then false
  when "nil", "null" then nil
  else
    return nil if context.nil?

    begin
      context[token]
    rescue StandardError
      nil
    end
  end
end

.parse(markup, context) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/fastcomments/jekyll/attribute_parser.rb', line 9

def parse(markup, context)
  result = {}
  return result if markup.nil?

  markup.scan(TOKEN_RE) do |key, double_quoted, single_quoted, bare|
    if !double_quoted.nil?
      result[key] = double_quoted
    elsif !single_quoted.nil?
      result[key] = single_quoted
    else
      value = coerce(bare, context)
      result[key] = value unless value.nil?
    end
  end

  result
end