module GraphqlGrpc::Arrayify

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: {1: :hello, 2: :world} => [{key:1, value: :hello}, {key:2, value: :world}]

Public Instance Methods

arrayify_hashes(input) click to toggle source
# 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_klass() click to toggle source
# 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