class ResponseMapper

Allows to map API response to domain language of your application

ResponseMapper.map(
  data: { order_number: 1, order_items: [1,2,3] }
  mapping: { order_number: :id, order_items: :items }
)

Returns nice Hash with proper naming which could be used to instantiate Order entity: { id: 1, items: [1,2,3] }

Constants

Error
VERSION

Attributes

data[R]
mapping[R]
symbolize_keys[R]

Public Class Methods

map(data:, mapping:, symbolize_keys: true) click to toggle source
# File lib/response_mapper.rb, line 19
def self.map(data:, mapping:, symbolize_keys: true)
  new(data, mapping, symbolize_keys).map
end
new(data, mapping, symbolize_keys) click to toggle source
# File lib/response_mapper.rb, line 31
def initialize(data, mapping, symbolize_keys)
  @data = data
  @mapping = mapping
  @symbolize_keys = symbolize_keys

  validate_mapping
end

Public Instance Methods

map() click to toggle source
# File lib/response_mapper.rb, line 23
def map
  map_data(data)
end

Private Instance Methods

map_array(array) click to toggle source
# File lib/response_mapper.rb, line 59
def map_array(array)
  array.each_with_object([]) do |entity, arr|
    if [Hash, Array].include?(entity.class)
      arr.push(map_data(entity))
    else
      arr.push(mapping.fetch(entity, entity))
    end
  end
end
map_data(data) click to toggle source
# File lib/response_mapper.rb, line 39
def map_data(data)
  case data
  when Hash then map_hash(data)
  when Array then map_array(data)
  else
    data
  end
end
map_hash(hash) click to toggle source
# File lib/response_mapper.rb, line 48
def map_hash(hash)
  hash.each_with_object({}) do |(k, v), result|
    k = k.to_sym if symbolize_keys

    mapped_value = [Hash, Array].include?(v.class) ? map_data(v) : v
    mapped_key = mapping.fetch(k, k)

    result[mapped_key] = mapped_value
  end
end
validate_mapping() click to toggle source
# File lib/response_mapper.rb, line 69
def validate_mapping
  message = 'Please, provide Hash with mapping, for example: { order_number: :id }' # rubocop:disable LineLength
  raise Error, message unless mapping.is_a?(Hash)

  raise Error, message if mapping.empty?
end