Skip to content

Instantly share code, notes, and snippets.

@jacklynrose
Created May 23, 2014 09:55
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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('=') && !@struct.respond_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