Created
November 21, 2014 00:56
-
-
Save asross/e82ef54e484806f3c1c3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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