views:

327

answers:

1

Hi!

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
  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!

A: 

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...)

jkrall
Well...How then would the require statements in vendor/plugins/mplug/lib/mplug.rb be?I still have to do like this in that file: require 'vendor/plugins/mplug/lib/mplug/indexer'
rejeep
Most plugins use init.rb to require files when Rails boots up.I suggest you review this Rails Guide: http://guides.rubyonrails.org/plugins.htmlIt gives the best practices for structuring your rails plugin directories, init.rb, requires, etc.
jkrall