Search code examples
ruby-on-railsrubyrubygemsrakerake-task

Determining whether gem was called as Rake task


I'm writing a gem that includes some rake tasks. I have some code in the before_configuration method that I want to run when my gem is loaded by the app at runtime, but NOT when a task is run with rake. How can I determine that?

lib/mygem/tasks.rake:

namespace :mygem do
  task :dosomething do   
    puts "DONE"
  end
end

lib/mygem/railtie.rb:

require "rails"
module Mygem
  class Railtie < ::Rails::Railtie
    config.before_configuration do
      #is_rake_task = ?
      if !is_rake_task
        # Do something
      end  
    end 
  end
end

Solution

  • Rake is only defined in rake context.

    So, you could simply go something like that :

    if defined? Rake
       # rake specific stuff
    else
       # non rake stuff
    end
    

    Edit :

    While this will work perfectly with rails s, there's a problem with zeus on development environment : zeus will require rake.

    If this is a problem, if think you can take advantage of Rake.application, which sets an instance variable when a rake task is executed.

    I've tested this in a zeus s context :

    > Rake.instance_variable_defined? :@application
    false
    

    And in a rake <task> context :

    > Rake.instance_variable_defined? :@application
    true
    

    So, a complete solution would be :

    if defined?( Rake ) and Rake.instance_variable_defined?( :@application )
       # rake specific stuff
    else
       # non rake stuff
    end