How can I choose which version of a module to include dynamically in Ruby?

前端 未结 3 1974
没有蜡笔的小新
没有蜡笔的小新 2021-02-20 07:20

I\'m writing a small Ruby command-line application that uses fileutils from the standard library for file operations. Depending on how the user invokes the applicat

3条回答
  •  被撕碎了的回忆
    2021-02-20 08:08

    Conditionally including the module through the send methods works for me as in the below tested example:

    class Artefact
      include HPALMGenericApi
      # the initializer just sets the server name we will be using ans also the 'transport' method : Rest or OTA (set in the opt parameter)
      def initialize server, opt = {}  
        # conditionally include the Rest or OTA module
        self.class.send(:include, HPALMApiRest) if (opt.empty? || (opt && opt[:using] opt[:using] == :Rest)) 
        self.class.send(:include, HPALMApiOTA) if (opt && opt[:using] opt[:using] == :OTA)    
        # ... rest of initialization code  
      end
    end
    

提交回复
热议问题