Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to include modules in rake task and make its methods available for the task in rails app?

In our rails 3.2.12 app, there is a rake task created under lib/tasks. The rake task needs to call a method find_config() which resides in another rails module authentify (module is not under /lib/). Can we include Authentify in rake task and make method find_config() available to call in the rake task?

Here is what we would like to do in the rake task:

include Authentify
config = Authentify::find_config()

Thanks for comments.

like image 972
user938363 Avatar asked Jun 25 '13 17:06

user938363


People also ask

Where do I put Rake tasks?

rake extension and are placed in Rails. root/lib/tasks . You can create these custom rake tasks with the bin/rails generate task command. If your need to interact with your application models, perform database queries and so on, your task should depend on the environment task, which will load your application code.


2 Answers

 require 'modules/module_name'

 include ModuleName

 namespace :rake_name do

 desc "description of rake task"

  task example_task: :environment do

   result = ModuleName::method_name()


  end #end task


 end

This works for me. Since your Module is not in /lib you might have to edit how it is required. But it should work. Hope it helps.

like image 124
zreitano Avatar answered Oct 12 '22 09:10

zreitano


PLEASE PAY ATTENTION TO THIS AND SAVE SOME RANDOM HEADACHES!! .
Don't include your module before your namespace:

include YourModule
namespace :your_name do
  desc 'Foo'
  task foo: :environment do
  end
end

or inside your namespace:

namespace :your_name do
  include YourModule

  desc 'Foo'
  task foo: :environment do
  end
end

as that will include your module for the whole app and it could bring you a lot of troubles (like me adding in the module some :attr_accessors and breaking factory-bot functioning or other things it has happened in the past for this same reason).
The "no issues" way is inside of your task's scope:

namespace :your_name do
  desc 'Foo'
  task foo: :environment do
    include YourModule
  end
end

And yes, if you have multiple tasks, you should include in each of them:

namespace :your_name do
  desc 'Foo'
  task foo: :environment do
    include YourModule
  end

  desc 'Bar'
  task bar: :environment do
    include YourModule
  end
end

or simply call your method directly if you're only calling a method once in the task:

namespace :your_name do
  desc 'Foo'
  task foo: :environment do
    YourModule.your_method
  end

  desc 'Bar'
  task bar: :environment do
    YourModule.your_method
  end
end
like image 26
Alter Lagos Avatar answered Oct 12 '22 09:10

Alter Lagos