0

Right now, I have a helper that contains about 1k+ lines of code. I am looking to move all of these methods into a subfolder within lib/custom/scripts/parsers/, but I'm not quite sure what changes I need to make to my workers so that I can continue to use all of these methods without an overly complicated process.

For example, I would like to put all of my methods into multiple files such as this:

  • lib/custom/scripts/parsers/ip_address_parser.rb
  • lib/custom/scripts/parsers/parser_two.rb
  • lib/custom/scripts/parsers/parser_three.rb

If I have a method, called hello_world inside of parser_two.rb, such as:

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

module ParserTwo
   def hello_world
      puts "Hello World"
   end
end

I would like to be able to directly access the method from the worker, such as:

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

Is there a way that I could just have a way to incorporate all of the modules within the lib/custom/scripts/parsers directory, and is there a way I can apply this inheritance to all of the workers?

When using helpers, I just do include HelperName and that's it, but it doesn't work the same in this scenario of course.

LewlSauce
  • 5,326
  • 8
  • 44
  • 91

1 Answers1

0

so what you can do is use ActiveSupport::Concern and nest modules inside modules like this:

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

then you can use AllParsers like that:

class RandomWorker
  include Sidekiq::Worker
  include AllParsers

  def perform
    hello_world
  end
end

still you maintain the ability to use just one module if needed:

class RandomWorker
  include Sidekiq::Worker
  include ParserTwo

  def perform
    hello_world
  end
end

Now about where to place them. If you want to place the modules inside the lib/something/directory you need to remember to load them properly. You can refer to this stackoverflow question:

Rails 5: Load lib files in production

beniutek
  • 1,672
  • 15
  • 32
  • I actually did something very similar to what you just mentioned with the exception of `ActiveSupport::Concern`. Everything else is pretty much exact same way. Thanks a lot! – LewlSauce Feb 09 '21 at 23:24