2013-03-27 64 views
0

我想要的是一個API,它根據通過初始化程序傳遞的參數來確定要委託方法的類。這是一個基本的例子:Ruby繼承和建議的方法?

module MyApp 
    class Uploader 
    def initialize(id) 
     # stuck here 
     # extend, etc. "include Uploader#{id}" 
    end 
    end 
end 

# elsewhere 
module MyApp 
    class UploaderGoogle 
    def upload(file) 
     # provider-specific uploader 
    end 
    end 
end 

我想要的結果:

MyApp::Uploader('Google').upload(file) 
# calls MyApp::UploaderGoogle.upload method 

請注意上面是僅用於演示目的。我將實際上傳遞一個包含上傳者ID屬性的對象。有沒有更好的方法來處理這個問題?

回答

1

沒有測試它,但如果你想include模塊:

module MyApp 
    class Uploader 
    def initialize(id) 
     mod = ("Uploader"+id).constantize 
     self.send(:include, mod) 
    end 
    end 
end 

如果你想用一個模塊擴展您的類:

module MyApp 
    class Uploader 
    def initialize(id) 
     mod = ("Uploader"+id).constantize 
     self.class.send(:extend, mod) 
    end 
    end 
end 
1

聽起來像你想要一個簡單的子類。 UploaderGoogle < Uploader上傳器定義了基本接口,然後子類定義了提供者特定的方法,根據需要調用super來執行上傳。未經測試的代碼OTTOMH以下...

module MyApp 
    class Uploader 
     def initialize(id) 
      @id = id 
     end 

     def upload 
      #perform upload operation based on configuration of self. Destination, filename, whatever 
     end 
    end 

    class GoogleUploader < Uploader 
     def initialize(id) 
      super 
      #google-specific stuff 
     end 

     def upload 
      #final configuration/preparation 
      super 
     end 
    end 
end 

沿着這些線的東西。根據傳遞的參數,我會使用case聲明。

klass = case paramObject.identifierString 
    when 'Google' 
     MyApp::GoogleUploader 
    else 
     MyApp::Uploader 
    end 

兩件事情:如果你在幾個地方這樣做,可能將其提取到一個方法。其次,如果您從用戶那裏獲得輸入信息,那麼如果您直接使用提供的字符串創建類名稱,則還需要進行大量的反注入工作。

+0

謝謝,我會嘗試! – 2013-03-27 15:56:16