Skip to content

Instantly share code, notes, and snippets.

@jacklynrose
Created May 23, 2014 09:55
Show Gist options
  • Save jacklynrose/6ecd13fda8ff9c6be879 to your computer and use it in GitHub Desktop.
Save jacklynrose/6ecd13fda8ff9c6be879 to your computer and use it in GitHub Desktop.
Half implementation of OpenStruct
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
@jacklynrose
Copy link
Author

Not using SimpleDelegator because I'd like to be able to use this with RubyMotion.

@hboon
Copy link

hboon commented Feb 14, 2018

Published as the gem motion-ostruct. Repo: https://github.com/hboon/motion-ostruct

Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment