Make rake task from gem available everywhere?

孤者浪人 提交于 2019-12-12 07:08:52

问题


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.


回答1:


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.




回答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



回答3:


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



回答4:


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.




回答5:


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



来源:https://stackoverflow.com/questions/742633/make-rake-task-from-gem-available-everywhere

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!