Skip to content

Instantly share code, notes, and snippets.

@davidjbeveridge
Forked from mrgenixus/Gemfile
Created March 28, 2012 03:01
Show Gist options
  • Save davidjbeveridge/2223192 to your computer and use it in GitHub Desktop.
Save davidjbeveridge/2223192 to your computer and use it in GitHub Desktop.
Attribute Observers
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