Ruby class instance variables and inheritance

前端 未结 9 672
日久生厌
日久生厌 2020-12-28 08:02

I have a Ruby class called LibraryItem. I want to associate with every instance of this class an array of attributes. This array is long and looks something lik

9条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-28 08:46

    Another solution would be to use the inherited hook:

    class LibraryItem < Object
      class << self
        attr_accessor :attributes
        def inherit_attributes(attrs)
          @attributes ||= []
          @attributes.concat attrs
        end
    
        def inherited(sublass)
          sublass.inherit_attributes(@attributes)
        end
      end
      @attributes = ['title', 'authors', 'location',]
    end
    
    class LibraryBook < LibraryItem
      @attributes.push('ISBN', 'pages')
    end
    

提交回复
热议问题