Created
April 16, 2011 15:00
-
-
Save eedrummer/923168 to your computer and use it in GitHub Desktop.
Reimplementing attr_accessor as an exercise in The Compleat Rubyist
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
module Properties | |
def property(property_name) | |
define_method(property_name) do | |
instance_variable_get("@#{property_name}".to_sym) | |
end | |
define_method("#{property_name}=".to_sym) do |value| | |
instance_variable_set("@#{property_name}".to_sym, value) | |
end | |
end | |
module InstanceMethods | |
def method_missing(method_name, *args) | |
@attrs ||= {} | |
md = method_name.to_s.match(/(set|get)_(.+)/) | |
if md | |
if md[1] == "set" | |
@attrs[md[2]] = args.first | |
else | |
@attrs[md[2]] | |
end | |
else | |
super(method_name, args) | |
end | |
end | |
end | |
def self.extended(klass) | |
klass.send(:include, InstanceMethods) | |
end | |
end | |
class Foo | |
extend Properties | |
property :bar | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment