Class: ShopifyCLI::TransformDataStructure

Inherits:
Object
  • Object
show all
Includes:
MethodObject
Defined in:
lib/shopify_cli/transform_data_structure.rb

Overview

‘TransformDataStructure` helps to standardize data structure access. It traverses nested data structures and can convert

  • all strings used as keys to symbols,

  • all strings used as keys from ‘CamelCase` to `snake_case` and

  • associative array containers, e.g. from Hash to OpenStruct.

Standardizing how a data structure is accessed greatly reduces the risk of subtle bugs especially when dealing with API responses.

TransformDataStructure.new(
  symbolize_keys: true,
  underscore_keys: true,
  associative_array_container: OpenStruct
).call([{"SomeKey" => "value"}]).tap do |result|
  result.value # => [#<OpenStruct: some_key: "value">]
end

Since ‘TransformDataStructure` is a method object, it can easily be chained:

require 'open-uri'
ShopifyCLI::Result
  .call { open("https://jsonplaceholder.typicode.com/todos/1") }
  .map(&TransformDataStructure.new(symbolize_keys: true, underscore_keys: true))
  .value # => { id: 1, user_id: 1, ... }

Instance Method Summary collapse

Methods included from MethodObject

included, #to_proc

Instance Method Details

#call(object) ⇒ Object



48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/shopify_cli/transform_data_structure.rb', line 48

def call(object)
  case object
  when Array
    shallow? ? object.dup : object.map(&self).map(&:value)
  when Hash
    object.each.with_object(associative_array_container.new) do |(key, value), result|
      result[transform_key(key)] = shallow? ? value : call(value).value
    end
  else
    ShopifyCLI::Result.success(object)
  end
end