Skip to content

Instantly share code, notes, and snippets.

@budu
Last active December 11, 2015 03:49
Show Gist options
  • Save budu/4541070 to your computer and use it in GitHub Desktop.
Save budu/4541070 to your computer and use it in GitHub Desktop.
class Hash
def as_object
HashObject.new self
end
end
#> o = { foo: (->(this) { puts this.bar }), bar: 'hello') }.as_object
#> o.foo
# => hello
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