Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I include helper methods in rake tasks

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

like image 242
Francisco Campaña Avatar asked Mar 12 '23 08:03

Francisco Campaña


1 Answers

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.

like image 162
max pleaner Avatar answered Mar 18 '23 04:03

max pleaner