Advanced Rails - Building Industrial-Strength Web Apps in Record Time

(Tuis.) #1

84 | Chapter 3: Rails Plugins


init.rb
This is a Ruby file run upon initialization of the plugin. Typically, it willrequire
files from thelib/directory. As many plugins patch core functionality,init.rbmay
extend core classes with extensions from the plugin:
require 'my_plugin'
ActionController::Base.send :include, MyPlugin::ControllerExtensions
Thesendhack is needed here becauseModule#includeis a private method and, at
least for now,send bypasses access control on the receiver.*


install.rb (not shown)
This hook is run when the plugin is installed with one of the automated plugin
installation tools such asscript/pluginor RaPT. It is a good idea not to do any-
thing mission-critical in this file, as it will not be run if the plugin is installed
manually (by checking out the source to a directory undervendor/plugins).
A typical use for theinstall.rbhook is to display the contents of the plugin’s
README file:
puts IO.read(File.join(File.dirname(_ FILE _), 'README'))


lib/
This is the directory in which all of the plugin code is contained. Rails adds this
directory to the Ruby load path as well as the RailsDependencies load path.
For example, assume you have a class, MyPlugin, inlib/my_plugin.rb. Since it is
in the Ruby load path, a simplerequire 'my_plugin'will find it. But since
Dependenciesautoloads missing constants, you could also load the file simply by
referring toMyPlugin in your plugin.


MIT-LICENSE (or other license file; not shown)
All plugins, no matter how small, should include a license. Failure to include a
license can prevent people from using your software—no matter how insignifi-
cant the plugin may be, it is against the law for someone else to distribute your
code without your permission.
For most projects, the MIT license (under which Rails itself is released) is suffi-
cient. Under that license, anyone can redistribute your software freely, provided
that they include a copy of the license (preserving your copyright notice). Includ-
ing theMIT-LICENSEfile in the plugin is important in this case, as it makes
compliance automatic.


Rakefile
This is the core Rake task definition file for the plugin. Usually it is used to
launch tests for the plugin itself or package the plugin for distribution.



  • In Ruby 1.9,Object#sendwill not automatically ignore access control on the receiving object, although the
    new methodObject#send! will.

Free download pdf