O'Reilly logo

Ruby Cookbook by Leonard Richardson, Lucas Carlson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

15.14. Refactoring the View into Partial Snippets of Views

Problem

Your view doesn't contain a lot of Ruby code, but it's still becoming more complicated than you'd like. You'd like to refactor the view logic into separate, reusable templates.

Solution

You can refactor a view template into multiple templates called partials. One template can include another by calling the render method, first seen in Recipe 15.5.

Let's start with a more complex version of the view shown in Recipe 15.5:

	<!-- app/ 
views/list/shopping_list.rhtml -->
	<h2>My shopping list</h2>

	<ul>
	 <% @list.each do |item| %>
	  <li><%= item.name %>
	   <%= link_to 'Delete', {:action => 'delete', :id => item.id},
	                  :post => true %>

	  </li>
	<% end %>
	</ul>

	<h2>Add a new item</h2>

	<%= form_tag :action => 'new' %>
	 Item: <%= text_field "product", "name" %>&#x00A;
	 <%= submit_tag "Add new item" %>
	<%= end_form_tag %>

Here's the corresponding controller class, and a dummy ListItem class to serve as the model:

	# app/controllers/list_controller.rb
	class ListController < ActionController::Base
	  def shopping_list
	    @list = [ListItem.new(4, 'aspirin'), ListItem.new(199, 'succotash')]
	  end

	  # Other actions go here: add, delete, etc.
	  # …
	end
	
	class ListItem
	  def initialize(id, name)
	    @id, @name = id, name
	  end
	end

The view has two parts: the first part lists all the items, and the second part prints a form to add a new item. An obvious first step is to split out the new item form.

We can do this by creating a partial view to print the new item form. To do ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required