class GraphQuery

Constants

CLOSE_BRACE
COMMA
OPEN_BRACE
VERSION

Public Class Methods

new(string_or_array) click to toggle source
# File lib/graph_query.rb, line 10
def initialize(string_or_array)
  @splited_array = if string_or_array.is_a?(Array)
      string_or_array
    else
      string_or_array.to_s
        .split(/({)|(,)|(})/)
        .select{|element| element.length > 0}
        .map(&:to_sym)
    end
end

Public Instance Methods

transform_to_array() click to toggle source
# File lib/graph_query.rb, line 21
def transform_to_array
  return @splited_array if [0, 1].include?(@splited_array.size)

  head_array, plain_comma, tail_array = partition_by_plain_comma
  if plain_comma
    GraphQuery.new(head_array).transform_to_array + GraphQuery.new(tail_array).transform_to_array
  else
    key = head_array[0]
    # 1 is "{" and -1 is "}"
    value = GraphQuery.new(head_array[2..-2]).transform_to_array
    [{key => value}]
  end
end

Private Instance Methods

partition_by_plain_comma() click to toggle source
# File lib/graph_query.rb, line 37
def partition_by_plain_comma
  head_array = []
  plain_comma = nil
  tail_array = []
  
  open_count = 0
  close_count = 0
  @splited_array.each_with_index do |element, index|
    open_count += 1 if element == OPEN_BRACE
    close_count += 1 if element == CLOSE_BRACE
    if element == COMMA && open_count == close_count
      plain_comma = element
      head_array = @splited_array[0..(index-1)]
      tail_array = @splited_array[(index+1)..-1]
      break
    end
  end

  raise OpenBraceError if open_count > close_count
  raise CloseBraceError if open_count < close_count
  
  head_array = @splited_array if plain_comma.nil?
  [head_array, plain_comma, tail_array]
end