4

I have methods that execute Nokogiri. i.e. Download pages, extract content, copy to another tables... etc.

This methods are inside helper that I need to run periodically by rake task.

Whats the proper way to call the methods in a task DRY.

Move code to task files Move to models, plain ruby Some other advice....?

Please provide an example of rake task including helper

BTW: I don't like to introduce jobs, due to adding another infrastructure issues. I'd prefer rake task for the moment. In the future I'd like to move to some background jobs framework like Sidekiq or similar

1 Answers1

7

When you define a rake task you can load your environment. From Using helpers in model: how do I include helper dependencies? I've learned you can include Helpers in models. Including them in a task should work as well.

task :my_task => :environment do
  include ActionView::Helpers
  # call a helper
end

From a DRY perspective I suppose this is fine - you're not repeating yourself.

But you could also define the code in a generic, globally accessible class/module and not have to use this include here.

You can define generic class/modules in any file in config/initializers and it will be accessible anywhere.

You can also use the lib directory if you add this line to config/application.rb:

config.autoload_paths << Rails.root.join('lib')

If you've written a module, you can then include it in your Helpers file.

But I'd say this is really a matter of preference. You basically have the same code either way, it's just a question of how it's organized.

Community
  • 1
  • 1
max pleaner
  • 26,189
  • 9
  • 66
  • 118
  • 1
    Good answer. Please improve it by adding specific helper like include ActionView::Helpers::Myhelper. Also "you can then include it in your Helpers file." Did you meant: "Include another module inside helper module"? – Francisco Campaña Aug 25 '16 at 18:25