Last active
August 29, 2015 14:11
-
-
Save kwstannard/5580a2923f12631e2912 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 SemiOpenStruct | |
def initialize(hash={}) | |
@hash = hash | |
end | |
def method_missing(method,*args,&block) | |
@hash[method] || | |
__try_hash_setter(method,*args,&block) || | |
super | |
end | |
def __try_hash_setter(method,*args,&block) | |
if m=method.to_s.match(/(\w*)=/) | |
@hash[m[1].to_sym] = args.first | |
end | |
end | |
def respond_to?(method) | |
@hash[method] || super | |
end | |
end | |
[1] pry(main)> require Dir.home + '/scripts/utility/semi_open_struct' | |
=> true | |
[2] pry(main)> sos=SemiOpenStruct.new({a: 1, b: 2}) | |
=> #<SemiOpenStruct:0x007fb931c4a4e0 @hash={:a=>1, :b=>2}> | |
[3] pry(main)> sos.c | |
NoMethodError: undefined method `c` for #<SemiOpenStruct:0x007fb931c4a4e0 @hash={:a=>1, :b=>2}> | |
from /Users/kstannard/scripts/utility/semi_open_struct.rb:9:in `method_missing` | |
[4] pry(main)> sos.c = 3 | |
=> 3 | |
[5] pry(main)> sos.c | |
=> 3 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment