Skip to content

Instantly share code, notes, and snippets.

@mike-bourgeous
Last active August 12, 2016 04:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mike-bourgeous/d7a9a05c296a8a1d6ddc73da209bcfb3 to your computer and use it in GitHub Desktop.
Save mike-bourgeous/d7a9a05c296a8a1d6ddc73da209bcfb3 to your computer and use it in GitHub Desktop.
A toy version of OpenStruct, with no error checking
# Faster than OpenStruct, but liable to get your box pwned.
class QuickAndDangerousStruct
def method_missing(name, *args)
make_method(name)
send name, *args
end
def make_method(name)
name = name.to_s
base = name.end_with?('=') ? name[0..-2] : name
var = "@#{base}"
eval <<-RUBY
define_singleton_method base do
#{var}
end
define_singleton_method "#{base}=" do |v|
#{var} = v
end
RUBY
end
end
# Faster than OpenStruct at retrieving keys that don't exist and for
# setting keys, but slower than OpenStruct for getting keys that exist
class QuickAndDirtyStruct
def method_missing(name, *args)
make_method(name)
send name, *args
end
def make_method(name)
name = name.to_s
base = name.end_with?('=') ? name[0..-2] : name
var = "@#{base}".to_sym
define_singleton_method base do
instance_variable_get(var)
end
define_singleton_method "#{base}=" do |v|
instance_variable_set(var, v)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment