2013-03-27 48 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