How do I replicate class_inheritable_accessor's behavior in Rails 3.1?

前端 未结 2 1931
Happy的楠姐
Happy的楠姐 2021-02-07 10:52

Beginning with Rails 3.1, class_inheritable_accessor produces deprecation warnings, telling me to use class_attribute instead. But class_attribut

2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-07 11:36

    Give this a try, a great way to have attributes set on the class, and not polluted by inheritance or instances.

    class Class
    
      private
    
      # Sets Unique Variables on a resource
      def inheritable_attr_accessor(*attrs)
        attrs.each do |attr|
    
          # Class Setter, Defining Setter
          define_singleton_method "#{attr}=".to_sym do |value|
            define_singleton_method attr do
              value
            end
          end
    
          # Default to nil
          self.send("#{attr}=".to_sym, nil)
    
          # Instance Setter
          define_method "#{attr}=".to_sym do |value|
            eval("@_#{attr} = value")
          end
    
          # Instance Getter, gets class var if nil
          define_method attr do
            eval("defined?(@_#{attr})") ? eval("@_#{attr}") : self.class.send(attr)
          end
    
        end
      end
    
    end
    

提交回复
热议问题