This repository has been archived by the owner on Jun 1, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 201
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
tosnake_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, ... }
call(object)
see source
# File lib/shopify-cli/transform_data_structure.rb, line 47
def call(object)
case object
when Array
object.map(&self).map(&: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
- ShopifyCli::MethodObject