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

Instance Method Summary collapse

Class Method Details

.call(fields) ⇒ Hash

Parses provided fields

Parameters:

  • fields (String, Hash, Array, nil)

Returns:

  • (Hash)

    parsed modifiers in form of nested hash



33
34
35
36
37
# File 'lib/serega/plugins/string_modifiers/parse_string_modifiers.rb', line 33

def self.call(fields)
  return fields unless fields.is_a?(String)

  new.parse(fields)
end

Instance 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: {} } } }

Parameters:

  • fields (String)

Returns:

  • (Hash)

    parsed modifiers in form of nested hash



52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/serega/plugins/string_modifiers/parse_string_modifiers.rb', line 52

def parse(fields)
  res = {}
  attribute = +""
  path_stack = nil

  fields.each_char do |char|
    case char
    when ","
      add_attribute(res, path_stack, attribute, FROZEN_EMPTY_HASH)
    when ")"
      add_attribute(res, path_stack, attribute, FROZEN_EMPTY_HASH)
      path_stack&.pop
    when "("
      name = add_attribute(res, path_stack, attribute, {})
      (path_stack ||= []).push(name) if name
    else
      attribute.insert(-1, char)
    end
  end

  add_attribute(res, path_stack, attribute, FROZEN_EMPTY_HASH)

  res
end