Skip to content

Instantly share code, notes, and snippets.

@thadeu
Last active September 22, 2022 15:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thadeu/1fe7b8633eb0b8b081baa1de5c210483 to your computer and use it in GitHub Desktop.
Save thadeu/1fe7b8633eb0b8b081baa1de5c210483 to your computer and use it in GitHub Desktop.
Ruby Deep OpenStruct
# frozen_string_literal: true
require 'bundler/inline'
gemfile do
source 'https://rubygems.org'
gem 'json', require: true
end
class Hash
def to_o
JSON.parse to_json, object_class: OpenStruct
end
end
response = {
body: {
status: 200,
errors: ['name is required'],
success: true,
data: { name: 'Thadeu' }
}
}.to_o
# before
p response['body']['errors']
# after
p response.body.success
p response.body.errors
p response.dig(:body, :data, :name)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment