首页 > 解决方案 > 如何实现所有在 Rails 工作人员中工作的层次结构或子模块?

问题描述

现在,我有一个包含大约 1k+ 行代码的助手。我希望将所有这些方法移动到 中的子文件夹中lib/custom/scripts/parsers/,但我不太确定我需要对我的工作人员进行哪些更改,以便我可以继续使用所有这些方法而无需过于复杂的过程。

例如,我想将所有方法放入多个文件中,例如:

如果我有一个称为hello_worldinside 的方法parser_two.rb,例如:

# lib/custom/scripts/parsers/parser_two.rb

module ParserTwo
   def hello_world
      puts "Hello World"
   end
end

我希望能够直接从工作人员访问该方法,例如:

class RandomWorker
  include Sidekiq::Worker
  sidekiq_options queue: Rails.env.to_sym, retry: 1

  def perform
    -> how to access hello_world method directly from parser_two.rb?
  end
end

有没有一种方法可以将所有模块合并到lib/custom/scripts/parsers目录中,有没有一种方法可以将此继承应用于所有工作人员?

使用助手时,我只是这样做include HelperName,仅此而已,但在这种情况下它当然不一样。

标签: ruby-on-railsruby

解决方案


所以你可以做的是在模块中使用ActiveSupport::Concern和嵌套模块,如下所示:

module ParserTwo
  extend ActiveSupport::Concern

  included do
    def hello_world
      puts "hello world!"
    end

    #...other methods
  end
end

module AllParsers
  extend ActiveSupport::Concern
  
  included do
    include ParserOne
    include ParserTwo
  end
end

那么你可以AllParsers这样使用:

class RandomWorker
  include Sidekiq::Worker
  include AllParsers

  def perform
    hello_world
  end
end

如果需要,您仍然可以只使用一个模块:

class RandomWorker
  include Sidekiq::Worker
  include ParserTwo

  def perform
    hello_world
  end
end

现在关于放置它们的位置。如果要将模块放置在其中,则lib/something/directory需要记住正确加载它们。你可以参考这个stackoverflow问题:

Rails 5:在生产中加载 lib 文件


推荐阅读