ruby-on-rails - 如何实现所有在 Rails 工作人员中工作的层次结构或子模块?
问题描述
现在,我有一个包含大约 1k+ 行代码的助手。我希望将所有这些方法移动到 中的子文件夹中lib/custom/scripts/parsers/
,但我不太确定我需要对我的工作人员进行哪些更改,以便我可以继续使用所有这些方法而无需过于复杂的过程。
例如,我想将所有方法放入多个文件中,例如:
- lib/custom/scripts/parsers/ip_address_parser.rb
- lib/custom/scripts/parsers/parser_two.rb
- lib/custom/scripts/parsers/parser_three.rb
如果我有一个称为hello_world
inside 的方法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
,仅此而已,但在这种情况下它当然不一样。
解决方案
所以你可以做的是在模块中使用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问题:
推荐阅读
- python - 使用 flask-sqlalchemy 创建应用程序模式
- c# - 无法使用 Fare 从复杂的正则表达式生成字符串
- node.js - 如何手动实现背压
- r - R 中的 Kruskal-wallis 测试给出错误:model.frame.default 中的错误:可变长度不同
- java - E/REALM_JNI: jni: ThrowingException 5, mmap() failed: Out of memory size: 369098752
- php - 图片上传失败(图片转换 Laravel)
- excel - 在特定 Windows 显示比例下调整大小时,InkPicture 呈现不正确
- c# - 使用 Moq 和接口进行单元测试
- php - 是否可以在 og 标签中为网站的不同页面添加自定义预览图像?
- java - 在 PlantUML 中呈现非 ASCII 字符所需的配置