Class: Semlogr::Templates::Parser

Inherits:
Object
  • Object
show all
Defined in:
lib/semlogr/templates/parser.rb

Constant Summary collapse

PROPERTY_TOKEN_START =
'{'
PROPERTY_TOKEN_END =
'}'
FILTER_TOKEN_START =
':'

Class Method Summary collapse

Class Method Details

.parse(template) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/semlogr/templates/parser.rb', line 17

def self.parse(template)
  return Template::EMPTY unless template && !template.empty?

  cached_template = @template_cache[template]
  return cached_template if cached_template

  tokens = []
  pos = 0

  while pos < template.size
    text_token, pos = parse_text_token(template, pos)
    tokens.push(text_token) if text_token

    property_token, pos = parse_property_token(template, pos)
    tokens.push(property_token) if property_token
  end

  @template_cache[template] = Template.new(template, tokens)
end

.parse_property_token(template, start) ⇒ Object



55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# File 'lib/semlogr/templates/parser.rb', line 55

def self.parse_property_token(template, start)
  return [nil, start] unless template[start] == PROPERTY_TOKEN_START

  token = nil
  pos = start
  filter_start = nil

  while pos < template.size
    case template[pos]
    when PROPERTY_TOKEN_END
      raw_text = template[start..pos]
      filter = nil

      if filter_start.nil?
        property_name = template[start + 1..pos - 1]
      else
        property_name = template[start + 1..filter_start - 1]
        filter = template[filter_start + 1..pos - 1]
      end

      token = PropertyToken.new(raw_text, property_name.to_sym, filter)
      return [token, pos + 1]
    when FILTER_TOKEN_START
      filter_start ||= pos
    end

    pos += 1
  end

  if pos > start
    text = template[start..pos - 1]
    token = TextToken.new(text)
  end

  [token, pos]
end

.parse_text_token(template, start) ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/semlogr/templates/parser.rb', line 37

def self.parse_text_token(template, start)
  token = nil
  pos = start

  while pos < template.size
    break if template[pos] == PROPERTY_TOKEN_START

    pos += 1
  end

  if pos > start
    text = template[start..pos - 1]
    token = TextToken.new(text)
  end

  [token, pos]
end