33

So I'm writing a small gem and I have a '/tasks' dir in it with some specific rake tasks. How do I make those tasks available automatically everywhere, where the gem is required? For example I wish I could run 'rake mygemrake:task' inside my rails root dir after I have the gem installed.

orion3
  • 9,797
  • 14
  • 67
  • 93

5 Answers5

22

For Rails3 applications, you might want to look into making a Railtie for your gem.

You can do so with:

lib/your_gem/railtie.rb

require 'your_gem'
require 'rails'
module YourGem
  class Railtie < Rails::Railtie
    rake_tasks do
      require 'path/to/rake.task'
    end
  end
end

lib/your_gem.rb

module YourGem
  require "lib/your_gem/railtie" if defined?(Rails)
end

Though, I had my share of difficulties with requiring the rake.task file in my railtie.rb. I opted to just define my measley one or two tasks within the rake_tasks block.

kelly.dunn
  • 1,546
  • 3
  • 16
  • 23
  • Just a word of warning, I couldn't get Rails to require `rake` tasks with a `.rake` extension using this method. – Benjamin Oakes Feb 01 '12 at 20:48
  • I think I remember the error being something akin to what's described here: http://blog.smartlogicsolutions.com/2009/05/26/including-external-rake-files-in-your-projects-rakefile-keep-your-rake-tasks-organized/ perhaps using `import` instead of `require` is the key to success? I'll dig into this next chance I get a free moment :) – kelly.dunn Feb 01 '12 at 22:52
  • @BenjaminOakes you could also replace `require` with `load`: `load "path/to/file.rake"` – Guilherme Garnier Jul 02 '13 at 14:46
  • Hi all, is there a way for creating a rake task without requiring rails? – nisevi Feb 17 '18 at 16:19
  • @nisevi it's perfectly fine to create rake task without requiring Rails, e.g. https://github.com/kjvarga/sitemap_generator/blob/master/lib/sitemap_generator/railtie.rb – lulalala Mar 02 '18 at 03:15
2

Check out the rdoctask in rake for an example of how to define a task provided by a gem. The task is defined in ruby instead of the rake build language and can be required like so:

require 'rake'             # the gem
require 'rake/rdoctask'    # the task
dstnbrkr
  • 4,305
  • 22
  • 23
0

You have to import those tasks in application's Rakefile. This is how it looks in mine (I am using bundler08 to manage my gems):

%w(gem1 gem2 gem3).each do |g|
  Dir[File.dirname(__FILE__) + "/vendor/bundler_gems/**/#{g}*/tasks/*.rake"].each do |f|
    import f
  end
end
skalee
  • 12,331
  • 6
  • 55
  • 57
0

You can write normal rake tasks for a gem and load them like this:

require 'rake'
load 'path/to/your/tasks.rake'

Also, take a look at thor vs. rake.

Community
  • 1
  • 1
Markus
  • 735
  • 6
  • 8
0

That's what Sake is for. Datamapper and Merb have been using Sake with success.

Bob Aman
  • 32,839
  • 9
  • 71
  • 95