How to add helpers, controllers, models, and views of your plugin into the Rails loadpath

Sometimes, when you’re writing a plugin, you end up writing models,
helpers, and controllers that the main app can use.  However, you
don’t want to copy it into the main app all the time.  You’d like to
keep things separate between the plugin, but you’d like to be able to
include it in the path of the main app.

To do this, put the following in your init.rb file in the root
of your plugin.  To add a new view path in your plugin that’s at
PLUGIN_ROOT/lib/views (where PLUGIN_ROOT is the root directory of your
plugin):


ActionController::Base.append_view_path(File.join(PLUGIN_ROOT, "lib", "views"))

Any template files (like html.erb) that you put in that path will be
seen in your app.

To add new helper, model, or controller directories in the rails load path:


%w{ helpers model controller }.each do |dir|
path = File.join(PLUGIN_ROOT, 'lib', dir)
$LOAD_PATH << path
Dependencies.load_paths << path
Dependencies.load_once_paths.delete(path)
end

And now, any models you put in lib/model, lib/controller, and
lib/helpers will be in the rails load path.

Of course, this might all be moot with the reintroduction of Rails
engines in 2.3.  I haven’t gotten around to using them or figuring it
out yet, but for now, this is how you do it with plugins.  tip!

Advertisements

2 thoughts on “How to add helpers, controllers, models, and views of your plugin into the Rails loadpath

  1. Hi Wilhelm,
    Im writing a plugin which contains controllers, views, helpers etc. For loading the views i tried using the above help.
    But it did not work .. please can you help me out on what might be going wrong
    Regards
    Hansraj

  2. This was for Rails 2.2.0. Since I don't know what your env is or what you did, I won't be much help. I suggest you ask in the rails mailing list. They'd be better able to help you there.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s