Skip to content
This repository has been archived by the owner on Jun 1, 2023. It is now read-only.

class ShopifyCli::TransformDataStructure

Kevin O'Sullivan edited this page Jun 28, 2021 · 1 revision

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 Methods

call

call(object)

see source

# File lib/shopify-cli/transform_data_structure.rb, line 47
def call(object)
  case object
  when Array
    object.map(&amp;self).map(&amp;:value)
  when Hash
    object.each.with_object(associative_array_container.new) do |(key, value), result|
      result[transform_key(key)] = call(value).value
    end
  else
    ShopifyCli::Result.success(object)
  end
end

Includes

  • ShopifyCli::MethodObject
Clone this wiki locally