开发者

Rails plugin require issues

I have a problem creating a Rails plugin, lets call it Mplug. The plugin is pretty much only a rake task, but with a library that the rake task uses.

The problem is to require files. Lets say that this is the rake task:

namespace :mplug do
  task :create do
    Mplug::Indexer.new
  end
end

This will not recognize the constant Mplug. So I thought I needed to require it.

require 'mplug'

namespace :mplug do
  task :create do
    Mplug::Indexer.new
  end
end

But then I get this message.

no such file to load -- mplug

So, ok. Lets try to give the path to the plugin then.

require 'vendor/plugins/mplug/lib/mplug'

namespace :mplug do
  task :create do
    Mplug::Indexer.new开发者_如何学C
  end
end

This actually works. However, except that I guess that this is a bad way to do it, I now have to require the files in my plugin as if I was in the rails root. For example:

module Mplug
end

require 'mplug/indexer'

Now has to be:

module Mplug
end

require 'vendor/plugins/mplug/lib/mplug/indexer'

Which I do not want to do of course.

Is there any neat way to solve this?

Thanks!


The easiest solution to this problem would be to register the rake task using the Rails::Railtie API. In lib/mplug.rb, define your Railtie:

module Mplug
  class Railtie < ::Rails::Railtie
    rake_tasks do
      load "mplug/rails.rake"
    end
  end
end

Then, in lib/mplug/rails.rake:

namespace :mplug do
  task :create do
    Mplug::Indexer.new
  end
end

Then, make sure your plugin is defined in your Gemfile. If your plugin is in vendor/plugins, add this line to your Gemfile:

gem "mplug", :path => "vendor/plugins/mplug"

If you push the plugin to a git repo, use :git.

Now, rake mplug:create will be available! If you want it to show up in rake -T, make sure you add a description:

namespace :mplug do
  desc "creating an mplug"
  task :create do
    Mplug::Indexer.new
  end
end


One option is to use the FILE constant, and then provide the rest of the path relative to the current file:

require File.join(File.expand_path(File.dirname(__FILE__)), '..', 'lib', 'mplug')

(if your rake task file is in your plugin_root/tasks...)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜