Ruby.Metaprogramming. class_eval

前端 未结 5 676
孤独总比滥情好
孤独总比滥情好 2020-12-18 16:50

There seem to be a mistake in my code. However I just can\'t find it out.

class Class
def attr_accessor_with_history(attr_name)
  attr_name = attr_name.to_s
         


        
5条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-18 17:29

    You will find a solution for your problem in Sergios answer. Here an explanation, what's going wrong in your code.

    With

    class_eval %Q{
     @#{attr_name}_history=[1,2,3]
    }
    

    you execute

     @bar_history = [1,2,3]
    

    You execute this on class level, not in object level. The variable @bar_history is not available in a Foo-object, but in the Foo-class.

    With

    puts f.bar_history.to_s
    

    you access the -never on object level defined- attribute @bar_history.

    When you define a reader on class level, you have access to your variable:

    class << Foo 
      attr_reader :bar_history
    end
    p Foo.bar_history  #-> [1, 2, 3]
    

提交回复
热议问题