Skip to content

Instantly share code, notes, and snippets.

@mikebannister
Created April 16, 2011 15:17
Show Gist options
  • Save mikebannister/923183 to your computer and use it in GitHub Desktop.
Save mikebannister/923183 to your computer and use it in GitHub Desktop.
class Object
def self.my_accessor(*accessor_names)
accessor_names.each do |name|
define_method name do
instance_var_name = "@#{name.to_s}".to_sym
self.instance_variable_get(instance_var_name)
end
writer_name = "#{name.to_s}=".to_sym
define_method writer_name do |value|
instance_var_name = "@#{name.to_s}".to_sym
self.instance_variable_set(instance_var_name, value)
end
end
end
end
class Person
my_accessor :moof
def initialize
@moof = 'foof'
end
end
me = Person.new
puts me
puts me.moof
me.moof = "woof"
puts me.moof
class Person
attr_accessor :attrs
def initialize
@attrs = {
:a => 1,
:b => 1
}
end
def get_thing key
@attrs[key]
end
def set_thing key, val
@attrs[key] = val
end
def method_missing(method_name, *values)
if method_name.to_s.match /^get_/
name = method_name.to_s.sub(/^get_/, '')
return get_thing(name.to_sym)
end
if method_name.to_s.match /^set_/
value = values[0]
name = method_name.to_s.sub(/^set_/, '').chop
return set_thing(name.to_sym, value)
end
end
end
m1 = Person.new
p m1.attrs
m1.set_c = 2
p m1.attrs
p m1.get_c
p m1.get_d
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment