2011-04-01 69 views
1

我有一个对象Animal,当我传入一个类型时,我选择其中一个子类并在那里实例化它。因此,像:Rails很生气,我正在实例化一个父类的孩子

class Museum::Animal 

    def initialize type 

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

但Rails的是给我的错误:预期..file路径../animal.rb定义动物

问题中的文件是在LIB /博物馆/ animal.rb

+0

这个类是什么文件,它在哪里? – lebreeze 2011-04-01 18:57:20

+0

它在lib/name_space/animal.rb – 2011-04-01 18:59:51

回答

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

有猫需要动物的继承方法,所以它们都必须是类而不是它们? – 2011-04-01 19:12:45

+1

@jeremy更新以反映继承 – Wes 2011-04-01 19:46:07

+0

@jeremy更新包括工厂获得动物类型 – Wes 2011-04-01 20:06:02