Skip to content

Instantly share code, notes, and snippets.

@edmore
Created May 1, 2012 15:57
Show Gist options
  • Save edmore/2569096 to your computer and use it in GitHub Desktop.
Save edmore/2569096 to your computer and use it in GitHub Desktop.
Meta programming Setters and Getters
class Object
def self.my_attr_accessible( *names )
names.each do |name|
define_method( "#{name}=" ) do |value|
instance_variable_set( "@#{name}", value )
end
define_method( name ) do
instance_variable_get( "@#{name}" )
end
end
end
end
class Developer
my_attr_accessible :level, :name, :surname
def initialize
yield (self) if block_given?
end
end
# Setters
superduperdev = Developer.new() do |d|
d.level = "journeyman"
d.name = "Edmore"
d.surname = "Moyo"
end
# Getters
1.9.3p125 :031 > superduperdev.name
=> "Edmore"
Edmore's IRB > superduperdev.surname
=> "Moyo"
Edmore's IRB > superduperdev.level
=> "journeyman"
Edmore's IRB > superduperdev.instance_variables
=> [:@level, :@name, :@surname]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment