Skip to content

Instantly share code, notes, and snippets.

@eedrummer
Created April 16, 2011 15:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save eedrummer/923168 to your computer and use it in GitHub Desktop.
Save eedrummer/923168 to your computer and use it in GitHub Desktop.
Reimplementing attr_accessor as an exercise in The Compleat Rubyist
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