284 | Chapter 9: Incorporating and Extending Rails
Notice that we do not need to close anything. The HTML tags are all closed for us,
but so is theeachiterator we opened. This style of code has a learning curve, but it
has less duplication overall than comparable template systems such as ERb.
The stable version of Haml can be installed as a Rails plugin from http://svn.
hamptoncatlin.com/haml/tags/stable. As with the other template language plugins, it
registers a template handler, so all you need to do is install the plugin and start writ-
ing views with an extension of.haml.
Incorporating Rails Components
As Rails is built up of many modular components, these components can be used
individually just as they can be used as a framework. Here we will see how the pieces
that make up Rails can be used in other Ruby code. We will walk through two mod-
ular components of Rails, ActiveRecord and ActionMailer, and see how to use them
in standalone applications.
ActiveRecord
ActiveRecord is perhaps the easiest component to decouple from the rest of Rails, as
it fulfills a purpose (object-relational mapping) that can be used in many different
places. The basic procedure for loading ActiveRecord is simple; just define the con-
nection, and then create the classes that inherit fromActiveRecord::Base:
require 'rubygems'
require 'active_record'
ActiveRecord::Base.establish_connection(
# connection hash
)
class Something < ActiveRecord::Base # DB table: somethings
end
Theestablish_connectionfunction takes a hash of parameters needed to set up the
connection. This hash is the same one that is loaded fromdatabase.ymlwhen using
Rails, so you could just pick up that file and load it:
require 'yaml' # Ruby standard library
ActiveRecord::Base.establish_connection(YAML.load_file('database.yml'))
If you are used to the features of edge Rails, you may not want to stick with the lat-
est gem version of ActiveRecord. To use the latest edge, first check out
ActiveRecord’s trunk from Subversion:
$ svn co http://svn.rubyonrails.org/rails/trunk/activerecord \
vendor/activerecord
Then, just require theactive_record.rb file from that directory:
require 'vendor/activerecord/lib/active_record'