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

前端 未结 3 1956
没有蜡笔的小新
没有蜡笔的小新 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 07:53

    If you would like to avoid the "switch" and inject the module, the

    def initialize(injected_module)
        class << self
            include injected_module
        end
    end
    

    syntax won't work (the injected_module variable is out of scope). You could use the self.class.send trick, but per object instance extending seems more reasonable to me, not only because it is shorter to write:

    def initialize(injected_module = MyDefaultModule)
        extend injected_module
    end
    

    but also it minimizes the side effects - the shared and easily changable state of the class, which can result in an unexpected behavior in a larger project. In Ruby the is no real "privacy" so to say, but some methods are marked private not without a reason.

提交回复
热议问题