ruby类中的可继承属性

时间:2010-09-24 11:29:12

标签: ruby class attributes class-attributes inherited

向所有人致以问候! 我想通过一个类来描述每种产品:

# Base product class
class BaseProduct
  prop :name, :price # Common properties for all inheritable products
end

class Cellphone < BaseProduct
  prop :imei # Concrete property for this product
end

class Auto < BaseProduct
  prop :max_speed, :color # Concrete properties for this product
end

c = Cellphone.new
c.prop_names # => [:name, :price, :imei]

a = Auto.new
c.prop_names # => [:name, :price, :max_speed, :color]

那么,如何实现呢?我花了3天时间却没有工作代码(

1 个答案:

答案 0 :(得分:3)

编辑:好的,试试这个:

class BaseProduct

  class << self
    def prop(*names)
      attr_accessor *names
      local_prop_names.push(*names)
    end

    def local_prop_names
      @local_prop_names ||= []
    end

    def prop_names
      if self == BaseProduct
        local_prop_names
      else
        superclass.prop_names + local_prop_names
      end
    end
  end

  def prop_names
    class << self; prop_names; end
  end
end

class BaseProduct
  prop :name
end

class Aero < BaseProduct
  prop :tricksy
end

class Heart < Aero
  prop :tiger
end

Aero.new.prop_names #=> [:name, :tricksy]
Heart.new.prop_names #=> [:name, :tricksy, :tiger]