Skip to content

Instantly share code, notes, and snippets.

@rondy
Created May 11, 2019 12:17
Show Gist options
  • Save rondy/88b62cfdb35d7040661fc18620c67f0f to your computer and use it in GitHub Desktop.
Save rondy/88b62cfdb35d7040661fc18620c67f0f to your computer and use it in GitHub Desktop.
class Hash
def self.to_ostruct(nested_hash_object)
require 'json'
require 'ostruct'
JSON.parse(nested_hash_object.to_json, object_class: OpenStruct)
end
def to_ostruct
self.class.to_ostruct(self)
end
end
class OpenStruct
def self.from_nested_hash(nested_hash_object)
Hash.to_ostruct(nested_hash_object)
end
end
nested_hash_object = { field: { nested_field: 'value of nested field' } }
Hash.to_ostruct(nested_hash_object) == nested_hash_object.to_ostruct
Hash.to_ostruct(nested_hash_object) == OpenStruct.from_nested_hash(nested_hash_object)
describe 'transforming hash to ostruct' do
specify 'transforms a nested hash object into a nested ostruct object' do
ostruct = { field: 'value of field' }.to_ostruct
expect(ostruct.field).to eq('value of field')
ostruct = { field: { nested_field: 'value of nested field' } }.to_ostruct
expect(ostruct.field.nested_field).to eq('value of nested field')
end
specify do
ostruct = OpenStruct.from_nested_hash({ field: 'value of field' })
expect(ostruct.field).to eq('value of field')
ostruct = OpenStruct.from_nested_hash({ field: { nested_field: 'value of nested field' } })
expect(ostruct.field.nested_field).to eq('value of nested field')
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment