2013-08-07 54 views
1

我一直在做一些'猴子补丁'(ahem请原谅我超人补丁),像这样,将下面的代码和更多的文件添加到文件中,在我"#{Rails.root}/initializers/"文件夹:继承自**其他**类,而不是实际的父类

module RGeo 
module Geographic 
class ProjectedPointImpl 
    def to_s 
    coords = self.as_text.split("(").last.split(")").first.split(" ") 
    "#{coords.last}, #{coords.first}" 
    end# of to_s 
    def google_link 
    url = "https://maps.google.com/maps?hl=en&q=#{self.to_s}" 
    end 
end# of ProjectedPointImpl class 
end# of Geographic module 
end 

我最终意识到,有两个不同的_Point_情况下,我想利用这些方法(它们都具有相同的格式,即熟知文本(WKT)字符串)并将上述两种方法的精确副本添加到某个RGeo::Geos::CAPIPointImpl类空间中。

我的话,在我年轻,没有经验的方式,想着干后(不要重复自己)的原则,着手创建一个特设类,我认为我也许可以从两个

继承
class Arghhh 
    def to_s 
    coords = self.as_text.split("(").last.split(")").first.split(" ") 
     "#{coords.last}, #{coords.first}" 
    end# of to_s 

    def google_link 
    url = "https://maps.google.com/maps?hl=en&q=#{self.to_s}" 
    end 
end 

,并告诉我的课,从它继承,即:ProjectedPointImpl < Arghhh

我被及时回应了红宝石这个错误,当我停下来,然后尝试重新加载我的rails控制台:

`<module:Geos>': superclass mismatch for class CAPIPointImpl (TypeError) 

...

我觉得我的天真在试图让CAPIPointImpl(在这种情况下),以继承另一个类比其父亮点关于这个问题我的知识差距非常明确

我可以使用什么方法实际上将额外的共享方法嫁接到来自其他独立父母的两个类上? ruby是否允许这些类型的抽象异常?

+0

Ruby不支持多重继承。如果您尝试重新打开一个已经定义的具有继承性但带有不同父级的类,那么您将得到您发布的错误。去看看模块,看看理查德库克下面说什么,你应该能够得到你想要的。 – xaxxon

回答

4

您需要做的是在模块中定义新方法,然后“混合”到现有类中。这里有一个草图:

# Existing definition of X 
class X 
    def test 
    puts 'X.test' 
    end 
end 

# Existing definition of Y 
class Y 
    def test 
    puts 'Y.test' 
    end 
end 

module Mixin 
    def foo 
    puts "#{self.class.name}.foo" 
    end 

    def bar 
    puts "#{self.class.name}.bar" 
    end 
end 

# Reopen X and include Mixin module 
class X 
    include Mixin 
end 

# Reopen Y and include Mixin module 
class Y 
    include Mixin 
end 

x = X.new 
x.test # => 'X.test' 
x.foo # => 'X.foo' 
x.bar # => 'X.bar' 

y = Y.new 
y.test # => 'Y.test' 
y.foo # => 'Y.foo' 
y.bar # => 'Y.bar' 

在这个例子中,我们有两个已经存在的类XY。我们定义了我们想要添加到XY中的方法,该方法被称为Mixin。然后,我们可以重新打开XY,并将模块Mixin包括在其中。完成后,XY都有其原始方法和Mixin中的方法。