Run initializer only for Rake tasks

I'd like a certain initializer to run when executing a Rake task, but not when running the Rails server.

What is the best way to differentiate a Rake invocation and a server invocation?

Answers


Rake allows you to specify dependencies for your tasks. The best recommended action would be for you to put your rake-specific initialization in its own task that in turn depends on the "environment" task. For example:

namespace :myapp do
    task :custom_environment => :environment do
        # special initialization stuff here
        # or call another initializer script
    end

    task :my_task => :custom_environment do
        # perform actions that need custom setup
    end
end

If you want to make a rake-specific directory of initializer scripts like we have for rails proper, we would just implement that in our :custom_environment task.

task :custom_environment => :environment do
    Dir.glob("config/rake-initializers/*.rb").each do |initializer|
        require initializer
    end
end

This allows you to keep rake-specific intializers separate from the regular initializers. You just have to remember to depend on the :custom_environment you set up.


Need Your Help

How do I use GAE datastore transactions with many-to-many relationships?

java google-app-engine jdo

I have a data module that includes Vendor objects and VendorCategory objects. Each vendor has multiple categories, and each category can have multiple vendors.

Test if Windows Hotfix is needed

windows windows-update hotfix

In a comment to Windows API equivalent to "WMIC QFE Get", Raymond Chen wrote that it is incorrect/useless to test if a hotfix is installed. The correct approach is to ask Windows Update i...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.