-
-
Save davidjbeveridge/2223192 to your computer and use it in GitHub Desktop.
Attribute Observers
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 ProofTest | |
class Model | |
def self.attr_reader property | |
define_method property do | |
puts "reading #{attributes[property]} from #{property}" | |
attributes[property] | |
end | |
end | |
def self.attr_writer property | |
define_method :"#{property}=" do |value| | |
attributes[property] = value | |
puts "setting #{property} to #{value}" | |
end | |
end | |
def self.attr_accessor property | |
attr_reader property | |
attr_writer property | |
end | |
def attributes | |
class << self | |
@attributes ||= Hash.new | |
end | |
end | |
end | |
end | |
module ProofTest | |
class Person < Model | |
attr_accessor :age | |
attr_accessor :name | |
end | |
end | |
david = ProofTest::Person.new | |
david.name = "David" | |
david.age = 25 | |
p david | |
p david.attributes | |
david.attributes.each do |attribute, value| | |
puts "Attribute #{attribute} is set to #{value}" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment