2014-01-17 31 views
0

下面的代碼:Ruby:我如何重構來自兩個模塊類方法的代碼?

module A 
    class C1 
    def self.grovel(x) 
     return A::helper(x) + 3 
    end 
    end 

    class C2 
    def self.grovel(x) 
     return A::helper(x) + 12 
    end 
    end 
    private 
    def helper(y) 
    y + 7 
    end 
    module_function :helper 
end 

f = A::C1.grovel(7) 
puts f 
puts A::C2.grovel(25) 

我與遺留代碼的工作,儘量避免改變太多。我不確定 我會用相同的方法創建兩個獨立的類,因爲每個類只有 包含一個方法,並帶有通用代碼。我想提取普通代碼 ,只有在一個方法可以看到,但仍然有 它的完全限定域名(「A ::幫手」)來調用它的方法。

有沒有更好的方法來做到這一點?理想情況下,我想換共同 代碼的方法(讓我們還是把它稱爲「幫手」),可以從類拜倒方法,而沒有任何資格內 被調用,但不容易 提供給外部的代碼模塊A.

感謝。

回答

0

Minixs是有用的,在適當的遺產不能被應用,例如,那麼類必須繼承的其他兩個類的屬性,因此,你可以只使用在繼承力學這裏:

module A 
    class C 
    def self.helper(y) 
     y + 7 
    end 
    end 

    class C1 < C 
    def self.grovel(x) 
     return self.helper(x) + 3 
    end 
    end 

    class C2 < C 
    def self.grovel(x) 
     return self.helper(x) + 12 
    end 
    end 
end 

puts A::C1.grovel(7) 
puts A::C2.grovel(25) 
1

如何創建另一個模塊?

module A 
    module Helper 
    def helper(y) 
     y + 7 
    end 
    end 

    class C1 
    class << self 
     include A::Helper  

     def grovel(x) 
     return helper(x) + 3 
     end 
    end 
    end 

    class C2 
    class << self 
     include A::Helper  

     def grovel(x) 
     return helper(x) + 12 
     end 
    end 
    end 


end 

puts A::C1.grovel(7) 
puts A::C2.grovel(25) 

您創建A的子模塊,並將其作爲Mixin包含在您的類中。這樣只有這些類可以訪問該方法。

你可以看到它在工作http://rubyfiddle.com/riddles/31313

+0

呀,這擾亂了現有的代碼最少。我想知道是否有metaprog方式找到當前模塊的方法並調用它,找不到它。 – Eric