Class: Serega::SeregaPlugins::StringModifiers::ParseStringModifiers

Inherits:
Object
  • Object
show all
Defined in:
lib/serega/plugins/string_modifiers/parse_string_modifiers.rb

Overview

Modifiers parser

Class Method Summary collapse

Class Method Details

.parse(fields) ⇒ Hash

Parses string modifiers

Examples:

parse("user") => { user: {} }
parse("user(id)") => { user: { id: {} } }
parse("user(id,name)") => { user: { id: {}, name: {} } }
parse("user,comments") => { user: {}, comments: {} }
parse("user(comments(text))") => { user: { comments: { text: {} } } }


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
77
78
79
80
81
82
83
84
# File 'lib/serega/plugins/string_modifiers/parse_string_modifiers.rb', line 49

def parse(fields)
  result = {}
  attribute_storage = result
  path_stack = (fields.include?(LPAREN) || fields.include?(RPAREN)) ? [] : nil

  start_index = 0
  end_index = 0
  fields.each_codepoint do |codepoint|
    case codepoint
    when COMMA_CODEPOINT
      attribute = extract_attribute(fields, start_index, end_index)
      add_attribute(attribute_storage, attribute, FROZEN_EMPTY_HASH) if attribute
      start_index = end_index + 1
    when LPAREN_CODEPOINT
      attribute = extract_attribute(fields, start_index, end_index)
      if attribute
        attribute_storage = add_attribute(attribute_storage, attribute, {})
        path_stack.push(attribute)
      end
      start_index = end_index + 1
    when RPAREN_CODEPOINT
      attribute = extract_attribute(fields, start_index, end_index)
      add_attribute(attribute_storage, attribute, FROZEN_EMPTY_HASH) if attribute
      path_stack.pop
      attribute_storage = dig?(result, path_stack)
      start_index = end_index + 1
    end

    end_index += 1
  end

  attribute = extract_attribute(fields, start_index, end_index)
  add_attribute(attribute_storage, attribute, FROZEN_EMPTY_HASH) if attribute

  result
end