Ruby.Metaprogramming. class_eval

前端 未结 5 660
孤独总比滥情好
孤独总比滥情好 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:37

    Here is what should be done. The attr_writer need be defined withing class_eval instead in Class.

    class Class
      def attr_accessor_with_history(attr_name)
        attr_name = attr_name.to_s
    
        attr_reader attr_name
        #attr_writer attr_name  ## moved into class_eval
    
        attr_reader attr_name + "_history"
    
        class_eval %Q{
          def #{attr_name}=(value)
            @#{attr_name}_history=[1,2,3]
          end
        }
    
    end
    end
    

提交回复
热议问题