views:

71

answers:

2

Greets to all! I want to describe each kind of product by a class:

# 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]

So, how to implement this? I spent 3 days on it but got no working code(

+2  A: 

EDIT: Okay, try this:

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]
banister
A: 

2 banister: I've tested your code:

class Car < BaseProduct
  prop :max_speed, :height
end

c = Car.new
c.prop_names # => [:max_speed, :height]

class WideCar < Car
  prop :width
end

wc = WideCar.new
wc.prop_names # => [:width], but it should be [:max_speed, :height, :width]
rbnoob
try my new edit
banister
well...does it do what you want?
banister
Wow! This is what I need, thanks! * dive into your code to understand how it working *
rbnoob
feel free to ask questions :)
banister