ruby - Having trouble with send and define_method -


i'm trying create custom attr_accessor, can't seem work. instead of returning value assigned writer, returns instance variable. ideas?

class object   def custom_attr_accessor(klass, attribute)     ivar = "@#{attribute}".to_sym     writer_body = lambda { |arg| instance_variable_set(ivar, arg) }     reader_body = lambda { ivar }     klass.send(:define_method, "#{attribute}=".to_sym, &writer_body)      klass.send(:define_method, "#{attribute}".to_sym, &reader_body)   end end  class person end  custom_attr_accessor(person, :age)  me = person.new me.age = 100 puts me.age 

=> @age

just did instance_variable_set, need instance_variable_get:

    reader_body = lambda { instance_variable_get(ivar) } 

btw, extending object , passing class not pretty. try make persion. custom_attr_accessor(:age), more oop.


Comments

Popular posts from this blog

java - Play! framework 2.0: How to display multiple image? -

gmail - Is there any documentation for read-only access to the Google Contacts API? -

php - Controller/JToolBar not working in Joomla 2.5 -