Skip to content

Instantly share code, notes, and snippets.

@asross
Created November 21, 2014 00:56
Show Gist options
  • Save asross/e82ef54e484806f3c1c3 to your computer and use it in GitHub Desktop.
Save asross/e82ef54e484806f3c1c3 to your computer and use it in GitHub Desktop.
class DeepOpenStruct
def initialize(hash)
hash.each { |k, v| define_singleton_method(k) {
instance_variable_get(:"@#{k}") || instance_variable_set(:"@#{k}", coerce(v))
} }
end
def [](k)
send(k)
end
def coerce(v)
case v
when Hash then DeepOpenStruct.new(v)
when Array then v.map(&method(:coerce))
else v
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment