
Hello again! I’ve been quite busy in between jobs and haven’t had much free time to work on my postings…well, let’s make up for lost time! Last time we spoke, I left you with a Rails app that made use of a basic relational database that contained books and associated authors. Let’s move the chains and introduce a few new concepts that you’ll be able to use with your own applications.
In this installment we’re going to create a landing page so visitors don’t get dumped to your book controller, use a partial, learn about the before_filter, and add some basic HTTP authentication.
if/for blocks and Rails’ partials
The first thing we’re going to do is create a new landing page so visitors don’t get dumped onto the scaffolding, but first reset the database. I had some random entries there I wanted to wipe out, we can do this with:
ng:bookstore ng$ rake db:reset
Next, we’ll be generating a new controller to handle the requests for our landing page; following convetion this controller will be plural…call it “homes”.
ng:bookstore ng$ script/generate controller homes
exists app/controllers/
exists app/helpers/
create app/views/homes
exists test/functional/
create app/controllers/homes_controller.rb
create test/functional/homes_controller_test.rb
create app/helpers/homes_helper.rb
ng:bookstore ng$
If you try to access http://localhost:3000/homes you’ll get a routing error; know what to do? Bingo! Let’s add a resource to our route and change the default map.root controller. I’ve removed the comments, but your routes.rb file should look similar to this:
ActionController::Routing::Routes.draw do |map|
map.resources :authors
map.resources :books
map.resources :homes
map.connect ':controller/:action/:id'
map.connect ':controller/:action/:id.:format'
map.root :controller => 'homes'
end
Now that our routes are set up, we need to create an index.html.erb file. We’ll place this in the apps/views/homes directory. You will be able to access the homes controller by either of these urls:
- http://localhost:3000/
- http://localhost:3000/homes
Our index file is quite barren right now, let’s add some code to so we can list our current book inventory. First, we need data to play with! Open your apps/controllers/homes_controller.rb and add an index method. Let’s pull all records from our database and make it available to our view.
class HomesController < ApplicationController
def index
@books = Book.find(:all)
end
end
Now that we’ve defined our data, we can loop through it using a basic for loop. I’ve set up the table structure with a header row, the individual rows are generated by our loop.
<table>
<tr>
<th>Title</th>
<th>Description</th>
</tr>
<% for book in @books %>
<tr>
<td><%=h book.title %></td>
<td><%=h book.description %></td>
</tr>
<% end %>
</table>
It essentially reads, “For each book in our @books collection, output a row with two columns. In in first column output an html escaped book title, in the second column output a html escaped book description. Once we’ve cycled through all the data in our @books collection, end the loop.”
I’m going to plug the above code into our index file.
<h1>Our Bookstore</h1>
<p>
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Vivamus sed nisi. Morbi aliquam ornare metus. Aliquam sed pede quis nulla porta rhoncus. Ut adipiscing aliquam enim. Sed laoreet justo in turpis. Aenean metus lorem, mollis elementum, pulvinar non, pharetra at, metus. Phasellus interdum tortor non tellus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Integer facilisis, erat sed aliquam tristique, mi augue tristique mauris, in mollis turpis tellus vel sem. Vivamus ac nibh ac lectus venenatis blandit. Morbi eget sem ac turpis sodales tincidunt. In in nunc commodo ante venenatis ornare. Aliquam sit amet ligula.
</p>
<h2>Current Inventory</h2>
<table>
<tr>
<th>Title</th>
<th>Description</th>
</tr>
<% for book in @books %>
<tr>
<td><%=h book.title %></td>
<td><%=h book.description %></td>
</tr>
<% end %>
</table>
<p>Aliquam vestibulum ultricies velit. Vivamus pulvinar urna. Mauris tincidunt blandit massa. </p>
Visit your bookstore. It looks kind of weird with no books eh? Let’s notify our visitors that we don’t have any books in stock; we’ll do this with a simple if statement.
<h1>Our Bookstore</h1>
<p>
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Vivamus sed nisi. Morbi aliquam ornare metus. Aliquam sed pede quis nulla porta rhoncus. Ut adipiscing aliquam enim. Sed laoreet justo in turpis. Aenean metus lorem, mollis elementum, pulvinar non, pharetra at, metus. Phasellus interdum tortor non tellus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Integer facilisis, erat sed aliquam tristique, mi augue tristique mauris, in mollis turpis tellus vel sem. Vivamus ac nibh ac lectus venenatis blandit. Morbi eget sem ac turpis sodales tincidunt. In in nunc commodo ante venenatis ornare. Aliquam sit amet ligula.
</p>
<% if @books.empty? %>
<h2>We don't have any books in stock, but they're coming!</h2>
<% else %>
<h2>Current Inventory</h2>
<table>
<tr>
<th>Title</th>
<th>Description</th>
</tr>
<% for book in @books %>
<tr>
<td><%=h book.title %></td>
<td><%=h book.description %></td>
</tr>
<% end %>
</table>
<% end %>
<p>Aliquam vestibulum ultricies velit. Vivamus pulvinar urna. Mauris tincidunt blandit massa. </p>
Pretty cool eh? It’s these little methods that make me smile! Let’s take another look at our index file…take a peek and ask yourself if anything looks out of place? Does that for loop bother you? It bothers me! I don’t like to see lots of code in my views…let’s get rid of it!
Rails has a handy feature called partials; partials are little fragments of code that can be included, and reused in your views. All partials take follow the same naming convention: “_filename.mimetype.erb”. Don’t worry about mimetypes right now, for the most part you’ll be something like _filename.html.erb or _filename.xml.erb. Create a new partial named named “book listings”, then place our if/for block in the partial.
<!-- _book_listings.html.erb -->
<% if @books.empty? %>
<h2>We don't have any books in stock, but they're coming!</h2>
<% else %>
<h2>Current Inventory</h2>
<table>
<tr>
<th>Title</th>
<th>Description</th>
</tr>
<% for book in @books %>
<tr>
<td><%=h book.title %></td>
<td><%=h book.description %></td>
</tr>
<% end %>
</table>
<% end %>
Now that we have a partial, we need to call it. render :partial => ‘partial_name’. Render the partial in our index view where our old if/for block was.
<!-- index.html.erb -->
<h1>Our Bookstore</h1>
<p>
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Vivamus sed nisi. Morbi aliquam ornare metus. Aliquam sed pede quis nulla porta rhoncus. Ut adipiscing aliquam enim. Sed laoreet justo in turpis. Aenean metus lorem, mollis elementum, pulvinar non, pharetra at, metus. Phasellus interdum tortor non tellus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Integer facilisis, erat sed aliquam tristique, mi augue tristique mauris, in mollis turpis tellus vel sem. Vivamus ac nibh ac lectus venenatis blandit. Morbi eget sem ac turpis sodales tincidunt. In in nunc commodo ante venenatis ornare. Aliquam sit amet ligula.
</p>
<%= render :partial => 'book_listings' %>
<p>Aliquam vestibulum ultricies velit. Vivamus pulvinar urna. Mauris tincidunt blandit massa. </p>
Rails’ before filter and basic HTTP authentication
Originally, I wanted to have us create a separate administrator section for administering the Books and Authors, but I think you’ll be able to do that on your own with the concepts we’ve worked on. Instead of a separate administrators section, let’s add some basic HTTP authentication to our Books and Authors controllers. By adding this authentication, we will be password protecting all calls to this controller. Here’s a snippet of code I use for basic access control:
def authenticate
authenticate_or_request_with_http_basic do |user_name, password|
user_name == "foo" && password == "bar"
end
end
If we placed this method in our Books controller with the rest of our methods, anybody could call it by visiting books/authenticate; instead we’re going to place in a walled garden. Using Rails you have two options to protect your methods: private and protected. If you’re curious what they both do, here’s an an excerpt from RubyLearning:
- Protected methods can be invoked only by objects of the defining class and its subclasses. Access is kept within the family. However, usage of protected is limited.
- Private methods cannot be called with an explicit receiver – the receiver is always self. This means that private methods can be called only in the context of the current object; you cannot invoke another object’s private methods.
We’ll be using the protected method, we can do this by wrapping it like so:
class BooksController < ApplicationController
# note: I've truncated the methods after index
before_filter :authenticate
# GET /books
# GET /books.xml
def index
@books = Book.find(:all)
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @books }
end
end
protected
def authenticate
authenticate_or_request_with_http_basic do |user_name, password|
user_name == "foo" && password == "bar"
end
end
You may have noticed before_filter :authenticate before all of our methods. This is part of the master plan! By adding a “before_filter” we’re asking Rails to call authenticate (which we’ve defined). As is, authenticate is called before any method; often you’ll have a situation where you only want to apply the before_filter to select methods. Check this out:
# apply authenticate to all methods
before_filter :authenticate
# apply authenticate to all methods EXCEPT index, and show
before_filter :authenticate, :except => [:index, :show]
# apply authenticate to ONLY the index and show
before_filter :authenticate, :only => [:index, :show]
So let’s review…in the previous section: we created a new landing page for our visitors, played with some if and for blocks, added basic HTTP authentication, and had a crash course on the before_filter. I’m sure you’ve been playing with the app in your browser, but if you haven’t…load up http://localhost:3000/books and you should be greeted with a familiar authentication dialog box!
Leave a comment, or send me an email with ideas for future articles! I wanted to cover SEO friendly URLs, validations, and a whole lot more this time but I wanted to get you guys an update sooner than later! Useful? Donate to my beer fund or digg this!
More Rails reading:
Understanding Rails partials