Last active
December 11, 2015 03:49
-
-
Save budu/4541070 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 Hash | |
def as_object | |
HashObject.new self | |
end | |
end | |
#> o = { foo: (->(this) { puts this.bar }), bar: 'hello') }.as_object | |
#> o.foo | |
# => hello |
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 HashObject | |
def initialize hash = {} | |
@hash = hash | |
end | |
def method_missing method, *args, &block | |
_, key, is_setter = /(\w+)(=)$/.match(method.to_s).to_a | |
result = @hash.has_key?(method) ? @hash[method] : @hash.default | |
return (@hash[key] = args.first) if is_setter | |
return result.is_a?(Proc) ? result[self, *args] : result | |
end | |
end | |
#> o = HashObject.new(foo: (->(this) { puts this.bar }), bar: 'hello') | |
#> o.foo | |
# => hello |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment