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



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

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



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
# File 'lib/serega/plugins/string_modifiers/parse_string_modifiers.rb', line 54

def parse(fields)
  res = {}
  attribute = +""
  char = +""
  path_stack = nil
  fields = StringIO.new(fields)

  while fields.read(1, 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