What's the variable scope within `class_eval` string?

后端 未结 1 1225
悲&欢浪女
悲&欢浪女 2021-02-01 07:39

I am using class_eval to write code to be executed under the context of current class. In the following code, I want to add a counter for changes of attribute value

相关标签:
1条回答
  • 2021-02-01 08:10

    it is not about class_eval it is about @count. if you define this variable at class level it will be a class instance variable not an instance variable.

    class Class
      def attr_count(attr_name)
        attr_name = attr_name.to_s
        attr_reader attr_name # create the attribute's getter
        class_eval %Q{
          def #{attr_name}= (attr_name)
            @attr_name = attr_name
            if @count
              @count += 1
            else
              @count = 1
            end
          end
    
          def #{attr_name}
            @attr_name
          end
        }
      end
    end
    
    class Foo
      attr_count :bar
    end
    
    f = Foo.new
    f.bar = 1
    
    0 讨论(0)
提交回复
热议问题