Last active
August 12, 2016 04:20
-
-
Save mike-bourgeous/d7a9a05c296a8a1d6ddc73da209bcfb3 to your computer and use it in GitHub Desktop.
A toy version of OpenStruct, with no error checking
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
# 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 |
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
# 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