Module: GraphqlGrpc::Arrayify

Included in:
Function
Defined in:
lib/graphql_grpc/arrayify.rb

Overview

Translate from gRPC hashmaps w/ integer keys to arrays of objects with ‘key’ and ‘value’ fields.

Recursively descend through the hash; if any hashes are encountered where all the keys are integers, convert that hash into an array of hashes with [{ key: <integer_value>, value: <the_value> },

{ key: <integer_value>, value: <the_value> },...]

Example: :hello, 2: :world => [value: :hello, value: :world]

Instance Method Summary collapse

Instance Method Details

#arrayify_hashes(input) ⇒ Object



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/graphql_grpc/arrayify.rb', line 36

def arrayify_hashes(input)
  case input.class.name.to_sym
  when :Array
    input.map { |i| arrayify_hashes(i) }
  when :Hash
    input_types = input.keys.map(&:class).compact.sort.uniq
    if input_types.inject(true) { |tf, val| val.ancestors.include?(numeric_klass) && tf }
      arr = input.to_a.map { |e| { key: e.first, value: e.last } }
      arrayify_hashes(arr)
    else
      input.each { |k, v| input[k] = arrayify_hashes(v) }
    end
  else
    input
  end
end

#numeric_klassObject



53
54
55
56
57
# File 'lib/graphql_grpc/arrayify.rb', line 53

def numeric_klass
  @numeric_klass ||= begin
    Gem::Version.new(RUBY_VERSION) < Gem::Version.new('2.4.0') ? Fixnum : Integer
  end
end