Created
May 23, 2014 09:55
-
-
Save jacklynrose/6ecd13fda8ff9c6be879 to your computer and use it in GitHub Desktop.
Half implementation of OpenStruct
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 OpenStruct < BasicObject | |
def initialize(hash) | |
@struct = ::Struct.new(*hash.keys.map { |k| k.to_sym }) | |
@struct = @struct.new(*hash.values) | |
end | |
def ==(other) | |
to_h == other.to_h | |
end | |
def method_missing(method_name, *args, &block) | |
if method_name.to_s.index('=') && [email protected]_to?(method_name) | |
vals = @struct.to_h.values | |
getter_name = method_name.to_s.gsub('=', '') | |
getters = ((@struct.to_h.keys.map { |k| k.to_sym }) + [getter_name.to_sym]) | |
@struct = ::Struct.new(*getters) | |
@struct = @struct.new(*vals) | |
end | |
@struct.send(method_name, *args, &block) | |
end | |
def respond_to_missing?(method_name, include_private = false) | |
return true if @struct.respond_to?(method_name) | |
return true if super | |
end | |
end | |
v = OpenStruct.new(:one => 'two') | |
p = OpenStruct.new(:one => 'two') | |
puts v | |
puts v == p |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Not using SimpleDelegator because I'd like to be able to use this with RubyMotion.