Sample Catalog Application using using JRuby and Rails
Posted by caroljmcdonald on October 10, 2007 at 5:20 PM EDT
Sample Store Catalog using using JRuby and Rails
The RRCatalog Sample app demonstrates the usage of JRuby and Rails to implement pagination of data sets for a Store Catalog.
download RRCatalog sample code
Overview of the Technologies and Frameworks in the Sample Application
Rails is a Model-View-Controller based framework for the development of database-backed web applications in Ruby.
JRuby is a 100%
pure-Java
implementation of the Ruby programming language. With JRuby and Rails
you get the advantage that you
can run your web app in a servlet container like Glassfish or
Tomcat.
The Sample Application
The Model
The Model is your application's persistent business domain objects. Rails implements the Active Record design pattern for the model. An ActiveRecord object instance represents a row in a database table. The item.rb and address.rb classes shown below were generated by Rails for the items and addresses tables. To learn how to generate Rails code with Netbeans 6 see Creating a Ruby Weblog in 10 Minutes . After model code generation you have to add the relationships. TheItem
class has a many-to-one relationship
with the Address
and Contactinfo classes. In Rails belongs_to
is the
many end of a many-to-one relationship, and has_many
is the one
end. In Rails the convention is that the object with the foreign key
belongs to the other object.
|
|
|
The Item class is a subclass of the Rails ActiveRecord Base class. At runtime the Rails framework dynamically adds column names, and attributes (with getters and setters) to the Item class for each column in the corresponding items table. Rails uses default mapping rules for this to work easily: the item class defaults to the items table, the address class to the addresses table, the primary key defaults to id, a foreign key defaults to tablename_id...
| SQL Sample for items table |
|
The Controller
Controllers handle incoming http requests, interact with the model to
get data and to process requests, invoke the correct view, and
direct domain data to the view for display.
In Rails, http requests are handled by ActionController classes which
are made up
of one or more action methods that are executed on request and then
either render
a template or redirect to another
action. Rails routes requests to the controller action which
corresponds to the URL mapping for the request. In Rails the default
mapping from URL to action method follows this convention: http://host/controller/action/id . For
example the URL
http://host/item/list calls the
list action method in the item controller class
shown below. Note
this code was generated using the Ruby Rails scaffolding support in the
NetBeans 6 IDE. Rails
Scaffolding provides a series of standardized
actions for listing, showing, creating, updating, and destroying
objects of a class. These standardized actions
come with both controller logic and default view templates (I modified
the view templates). The ItemController
list
action renders a view with a paginated list of item objects.| Code Sample from: app/controllers/item_controller.rb |
class ItemController < ApplicationController def index list render :action => 'list' end def list @item_pages, @items = paginate :items, :per_page => 10 end |
The ItemController is a subclass of ApplicationController which is a subclass of the Rails ActionController Base class. When a URL has a controller but no action (e.g. http://host/controller/ ), Rails defaults to the index action. In the ItemController code the index action method redirects to the list action. The list action method calls the ActionController paginate method which queries the Item Active Record model for pagination. The pagination method creates the @items instance variable, which is an ordered collection of model objects for the current page (at most 10), and a @item_pages paginator instance, which is a class representing a paginator for an Active Record collection. The @item_pages and @items variables are automatically made available to the list view by the framework.
After executing code, actions usually render a template in the views directory corresponding to the name of the controller and action, for example the list action will render the app/views/item/list.rthml template.
The View
The view layer generates a web
page, using data from domain objects provided by the controller. In
Rails, the view is rendered using RHTML
, RXML, or RJS. RHTML is HTML with
embedded Ruby code.| Code Sample from: app/views/item/list.rhtml |
|
The view uses instance variables set by the controller to access the data it needs to render the rhtml. In the list.rhtml:
<% for
item in @items %>
loops through the objects in the @items instance
variable, which is an ordered collection of
Item model
objects, and assigns each Item
model object to the item variable.<%=
link_to
%Q{#{item.name}}, :action => 'show', :id => item %>
calls the Rails helper method
link_to, which
creates an html link to the item/show/id action which will display the
corresponding item details. Rails helpers
are methods that help your view templates generate HTML. For
example this line will generate the following HTML for one item:
<a href="/item/show/1">Friendly Cat</a>
<%=
image_tag
item.imagethumburl %> calls the Rails helper method
image_tag,
which generates an HTML image tag for the
item's
imagethumburl attribute. <%=h
item.price %> displays the value of the
item 's price attribute.The
Rails h method creates
escaped HTML text.<%=
link_to 'Previous page',{:page =>
@item_pages.current.previous} if
@item_pages.current.previous %>creates an html link to the previous
page of items, using the @item_pages
paginator instance, if there is a previous page.
The Show Action Method
In Rails the mapping for the URL http://host/item/show/1 (
http://host/controller/action/id ) to
action method will
route to the show
action method in the ItemController
passing 1 to the method as the id
member of the params parameter
hash. The show
action method of the ItemController class
is shown below. The ItemController
show
action renders a view showing the details of the item object
corresponding to the id parameter.| Code Sample from: app/controllers/item_controller.rb |
def show @item = Item.find(params[:id]) end |
The show action method calls the Item
ActiveRecord Base class find method
which queries the items table creating the @item instance
variable corresponding to the item with the attribute id (primary key)
equal to the id
parameter. This is the equivalent of the following sql : select * from items where id='1' .
The @item variable
is automatically made available to the Show view by the framework.The Show View Template
After executing
code in the action, the show action
renders the app/views/item/show.rthml template. Below is the RHTML for
the item show view : | Code Sample from: app/views/item/show.rhtml |
|
<%=h
@item.description%>
displays the value of the
item 's description attribute,
in escaped HTML text.<%=
image_tag
@item.imageurl %> generates an HTML
image tag for the
item's imageurl
attribute.
<%=h
@item.address.city%>
displays the value of the
item's address city attribute,
in escaped HTML text.The image below shows the resulting page for the url http://host/item/show/id, which displays the item's details:
Layout Templates
Rails layout templates let you put common html on multiple views (for example page headers, footers, sidebars). By default layout templates are in the views layouts directory with a file name corresponding to the controller. To add a title and parrot image to the top of the Pet Catalog pages, I put this table in the app\views\layouts\item.rhtml template:| Code Sample from: app/views/layouts/item.rhtml |
<table> <tr> <td>Pet Catalog</td> <td><img src="/images/banner_logo.gif"></td> </tr> </table> |
Conclusion
This concludes the sample application which demonstrates how to work with JRuby and Rails to page through a list of Item Model objects which are retrieved using Item Controller action methods, and displayed using Item rhtml View templates.
Running the Sample Application:
Setting Things Up
- Download
and install NetBeans 6.0 Beta 1. Get the full distribution so you can
get the Java IDE, Ruby and GlassFish.
- Configure JRuby to use the
Derby Database (by default Ruby uses MySQL, but I use Derby
because I like it. If you prefer MySQL, then ignore this , change
the
RRCatalog\config\database.yml file, and add the tables below to your
MySQL db )
- Open the Tools Options dialog to find the location of your JRuby interpreter.
- Copy the following jar to your JRuby lib directory: derbyclient.jar (Tools > Java DB Database > Settings will give you the location of derbyclient.jar)
Open and Run the Sample code:
- Download the sample
code and extract its contents. You should now see the newly
extracted directory as
<sample_install_dir>/RRCatalog, where<sample_install_dir>is the directory where you unzipped the sample package. For example, if you extracted the contents toC:\on a Windows machine, then your newly created directory should be atC:\RRCatalog.
- Start the NetBeans IDE. Click Open Project in the File menu and
select
the
RRCatalogdirectory you just unzipped.
- Start the Java DB database as follows:
- Select Java DB Database in the Tools menu.
- Select Start Java DB Server.
- Select Java DB Database in the Tools menu.
- Add a connection to the Java DB database as follows:
- Select the Services Tab on the left.
- Select Databases, Right mouse click and select New Connection.
- In the New DB Connection window:
for Name: select Java DB (Network)
for URL enter: jdbc:derby://localhost:1527/pet-catalog
for username enter: app , for password enter: app
- Select the Services Tab on the left.
- Create the tables in the pet-catalog database as follows:
- Under Databases, select the connection pet-catalog that you
just created. Right mouse click and select Connect.
- enter the username app and password app.
- Right mouse click on pet-catalog and select Excecute Command.
- In the SQL command window copy paste all the sql text from
the file
<sample_install_dir>/RRCatalog/catalog.sql,
- At the top of the window click on the icon for Run SQL. This
will create all of the tables and data for the application.
- Under Databases, select the connection pet-catalog that you
just created. Right mouse click and select Connect.
- Run the project as follows:
- Right click the
RRCatalognode in the Projects window.
- Select Run. This will run the Application with the
WEBrick server.
- Right click the
When you run the project, your browser should display the List Items page of the Sample Application (at http://localhost:3000/).Run the Sample code on Glassfish:
- Use the WAR file in
<sample_install_dir>/RRCatalog/RRCatalog.waror Create a WAR file:
- In the NetBeans IDE, right-select the project, select
Run Rake Target, war, standalone, create
- In the NetBeans IDE, right-select the project, select
- Copy the WAR file (
RRCatalog.war) to your Glassfish installation "domains/domain/autodeploy" directory.
- Enter the URL http://localhost:8080/RRCatalog/ in
your browser, you should see the display the List Items
page of the Sample Application.
References
- To learn how to build a Ruby Rails app froms scratch see: Creating
a
Ruby Weblog with Netbeans 6 in 10 Minutes
- To learn how to run a JRuby app on Glassfish see: JRuby on Rails, NetBeans 6 and GlassFish V2 - Simplified Steps
- To learn how to run a JRuby app on Glassfish using the Derby db
see: Using
JavaDB with JRuby on Rails
- Rails framework
documentation
- Ruby on Rails Wiki
- What is Ruby on Rails article
- JRuby Inside web site
- Ruby on Rails: Up and Running Book
- Rails for Java
Developers book
Related Topics >>
Blog Links >>
- Login or register to post comments
- Printer-friendly version
- caroljmcdonald's blog
- 4517 reads





