Making XML in a Rails App
Ruby on Rails is a database-based web framework. An XML document
may be created and parsed with Ruby on Rails. Rails provides a Ruby
library called Builder to generate XML markup. The
Builder package contains class
Builder::XmlMarkup to generate an XML document. In
this article, we will create an XML document from a database table
with the Builder library.
Installing XML Builder
Before installing Builder, we need to install the Ruby on Rails
framework and RubyGems, the standard Ruby package manager. Download
the Ruby Windows
Installer application and double-click the
ruby185-21.exe application. When Ruby Setup Wizard gets
started, click on Next and accept the license agreement.
Select the default components to install, including the
RubyGems package manager. Specify a directory to install Ruby
c:/ruby is the default) and click Next. Specify
a Start menu folder and click on Install to install Ruby and
RubyGems. Next, install Rails. From the
directory--the directory in which Ruby is installed--run the
following command to install Rails and dependencies.
c:/ruby>gem install rails --include-dependencies
Builder is included with the package manager RubyGems. Run the following command to install Builder 2.0.0.
C:/ruby>gem install builder
Builder::XmlMarkup class provides the methods discussed
in Table 1.
||Adds a CDATA section.|
||Adds a comment.|
||Adds a declaration.
||Adds a processing instruction. Attributes are specified with an array of hash entries.|
||Creates an XML markup
||Returns target of
We also need to install the MySQL database for creating an XML
document from the database. Download MySQL
5.0. Install MySQL 5.0 with
Setup.exe and create a
MySQL Server instance.
Creating an XML Document from a Database
In this section we will create an XML document from a database table. Create a Rails application for generating an XML document from a database:
development mode settings in the
app/config/database.yml file to specify the database
test. The development mode settings for the MySQL database are
shown in the following listing.
development: adapter: mysql database: test username: root password: nil host: localhost
We will use
ActiveRecord migrations to create a
database table. Create a migration script by creating a model
script with the following Ruby command:
C:\ruby\databasexml> ruby script/generate model catalog
A model script
app/models/catalog.rb and a
created. The migration script class,
ActiveRecord::Migration class as shown in the
class CreateCatalogs < ActiveRecord::Migration def self.up create_table :catalogs do |t| # t.column :name, :string end end def self.down drop_table :catalogs end end
Pages: 1, 2