2011-04-01 3 views
1

私はオブジェクトAnimalを持ち、型を渡すとサブクラスの1つを選択してインスタンス化します。だから、のようなもの:動物にRailsは親クラスから子をインスタンス化することに怒っています

問題のファイルはlibにある/美術館/ animal.rbを定義することが予想される..FILEパス../animal.rb:

class Museum::Animal 

    def initialize type 

     case type 
     when "cat" 
      CatAnimal.new 
     when "dog" 
      DogAnimal.new 
     end 
    end 
end 

しかし、Railsは私にエラーを与えています

+0

そのクラスはどのファイルにありますか? – lebreeze

+0

lib/name_space/animal.rbにあります –

答えて

2
module Barn 
    # parent class 
    class Animal 
    def say 
     'default' 
    end 
    end 

    # inheritance for cat 
    class Cat < Animal 
    def say 
     "meow" 
    end 
    end 

    #inheritance for dog 
    class Dog < Animal 
    end 

    # Factory to get by "type" 
    def self.get type 
    case type 
    when :dog 
     Dog.new 
    when :cat 
     Cat.new 
    end 
    end 
end 

これをlib/barn.rbとして保存します。次に、あなたはできます:

require 'barn' 

c = Barn.get :cat 
=> #<Barn::Cat:0x0000010719ffe8> 
c.say 
=> "meow" 

d = Barn.get :dog 
=> #<Barn::Dog:0x00000107190408> 
d.say 
=> "default" 
+0

猫が動物から必要とする継承されたメソッドがあるので、両方ともクラスでなければなりませんか? –

+1

@jeremy継承を反映するように更新されました – Wes

+0

@jeremy動物をタイプ別に取得するための工場を含めるように更新しました – Wes

関連する問題