Skip to content

Instantly share code, notes, and snippets.

@djberg96
Last active August 29, 2015 14:23
Show Gist options
  • Save djberg96/567dc74889e20d584578 to your computer and use it in GitHub Desktop.
Save djberg96/567dc74889e20d584578 to your computer and use it in GitHub Desktop.
Instance variable aliasing
require 'ostruct'
require 'delegate'
require 'json'
class Foo < Delegator
def initialize(json)
@ostruct = JSON.parse(json, object_class: OpenStruct)
__setobj__(@ostruct)
end
protected
def __getobj__
@ostruct
end
def __setobj__(obj)
obj.methods(false).each{ |m|
if m.to_s[-1] != '='
res = obj.send(m)
if res.is_a?(OpenStruct)
__setobj__(res)
end
end
snake = m.to_s.gsub(/(.)([A-Z])/,'\1_\2').downcase.to_sym
obj.instance_eval("alias #{snake} #{m}")
}
end
end
json_string = '
{
"firstName":"jeff",
"lastName":"durand",
"address": {
"streetAddress":"22 charlotte rd",
"zipCode":"01013"
}
}
'
f = Foo.new(json_string)
p f.firstName # works
p f.first_name # works
p f.address.streetAddress # works
p f.address.street_address # OOPS
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment