Evaluation. Chapter 1: An Overview Of Ruby Rails. Copy. 6) Static Pages Within a Rails Application... 1-10



Similar documents
Ruby on Rails is a web application framework written in Ruby, a dynamically typed programming language The amazing productivity claims of Rails is

Outline. Lecture 18: Ruby on Rails MVC. Introduction to Rails

Integrate Rails into an Existing IIS Web infrastructure using Mongrel

Ruby On Rails. CSCI 5449 Submitted by: Bhaskar Vaish

Rails 4 Quickly. Bala Paranj.

Monitoring Oracle Enterprise Performance Management System Release Deployments from Oracle Enterprise Manager 12c

Test Automation Integration with Test Management QAComplete

Drupal CMS for marketing sites

Witango Application Server 6. Installation Guide for OS X

Pete Helgren Ruby On Rails on i

Ipswitch Client Installation Guide

Oracle Fusion Middleware 11gR2: Forms, and Reports ( ) Certification with SUSE Linux Enterprise Server 11 SP2 (GM) x86_64

Sample copy. Introduction To WebLogic Server Property of Web 10.3 Age Solutions Inc.

Guides.rubyonrails.org

The Other mod_rails: Easy Rails Deployment with JRuby. Nick Sieger Sun Microsystems, Inc

Working With Virtual Hosts on Pramati Server

Application. 1.1 About This Tutorial Tutorial Requirements Provided Files

CS169.1x Lecture 5: SaaS Architecture and Introduction to Rails " Fall 2012"

Ruby on Rails (Ruby 1.9.2, Rails 3.1.1) Installation

Apache Server Implementation Guide

Administration Quick Start

1. Was ist das? II. Wie funktioniert das? III. Wo funktioniert das nicht?

PowerTier Web Development Tools 4

Secure Messaging Server Console... 2

Getting Started using the SQuirreL SQL Client

The NetBeans TM Ruby IDE: You Thought Rails Development Was Fun Before

EVALUATION ONLY. WA2088 WebSphere Application Server 8.5 Administration on Windows. Student Labs. Web Age Solutions Inc.

Introduction to Ingeniux Forms Builder. 90 minute Course CMSFB-V6 P

Chapter 1 - Web Server Management and Cluster Topology

Rails Cookbook. Rob Orsini. O'REILLY 8 Beijing Cambridge Farnham Koln Paris Sebastopol Taipei Tokyo

Hudson Continous Integration Server. Stefan Saasen,

DEPLOYING EMC DOCUMENTUM BUSINESS ACTIVITY MONITOR SERVER ON IBM WEBSPHERE APPLICATION SERVER CLUSTER

WebLogic Server: Installation and Configuration

Magento Search Extension TECHNICAL DOCUMENTATION

NSi Mobile Installation Guide. Version 6.2

Enterprise Service Bus

TIBCO ActiveMatrix BusinessWorks Plug-in for TIBCO Managed File Transfer Software Installation

Wakanda Studio Features

An Oracle White Paper January Integrating Oracle Application Express with Oracle Access Manager. Revision 1

Deep in the CRUD LEVEL 1

Using the Adobe Access Server for Protected Streaming

Novell Identity Manager

Installing Rails 2.3 Under Windows XP and Apache 2.2

FileMaker Server 12. FileMaker Server Help

IBM WebSphere Application Server Version 7.0

MassTransit 6.0 Enterprise Web Configuration for Macintosh OS 10.5 Server

Crystal Reports Installation Guide

Modern Web Application Framework Python, SQL Alchemy, Jinja2 & Flask

Application Servers - BEA WebLogic. Installing the Application Server

Web Server Manual. Mike Burns Greg Pettyjohn Jay McCarthy November 20, 2006

Building and Deploying Web Scale Social Networking Applications Using Ruby on Rails and Oracle. Kuassi Mensah Group Product Manager

virtualization.info Review Center SWsoft Virtuozzo (for Windows) //

CYCLOPE let s talk productivity

Using Actian PSQL as a Data Store with VMware vfabric SQLFire. Actian PSQL White Paper May 2013

Integrated Virtual Debugger for Visual Studio Developer s Guide VMware Workstation 8.0

COMMANDS 1 Overview... 1 Default Commands... 2 Creating a Script from a Command Document Revision History... 10

PaaS Operation Manual

Document management and exchange system supporting education process

WIRIS quizzes web services Getting started with PHP and Java

ZeroTurnaround License Server User Manual 1.4.0

Creating a Java application using Perfect Developer and the Java Develo...

Creating Home Directories for Windows and Macintosh Computers

Deploying Intellicus Portal on IBM WebSphere

WEB2CS INSTALLATION GUIDE

Oracle Service Bus Examples and Tutorials

JBoss Portlet Container. User Guide. Release 2.0

MarkLogic Server. Connector for SharePoint Administrator s Guide. MarkLogic 8 February, 2015

Handle Tool. User Manual

Customizing the SSOSessionTimeout.jsp page for Kofax Front Office Server 3.5.2

Installation Guide for WebSphere Application Server (WAS) and its Fix Packs on AIX V5.3L

10CS73:Web Programming

Novell ZENworks 10 Configuration Management SP3

Intellicus Cluster and Load Balancing (Windows) Version: 7.3

App Building Guidelines

Stock Trader System. Architecture Description

To install Multifront you need to have familiarity with Internet Information Services (IIS), Microsoft.NET Framework and SQL Server 2008.

Developing ASP.NET MVC 4 Web Applications MOC 20486

Setting Up SSL on IIS6 for MEGA Advisor

OpenMind: Know Your Customer

What s really under the hood? How I learned to stop worrying and love Magento

How To Set Up An Intellicus Cluster And Load Balancing On Ubuntu (Windows) With A Cluster And Report Server (Windows And Ubuntu) On A Server (Amd64) On An Ubuntu Server

McAfee One Time Password

KonyOne Server Installer - Linux Release Notes

CatDV Pro Workgroup Serve r

Novell Identity Manager

Installing Rails 2.3 Under CentOS/RHEL 5 and Apache 2.2

Developing Web Views for VMware vcenter Orchestrator

SOA Software API Gateway Appliance 7.1.x Administration Guide

Thin Client Manager. Table of Contents. 1-10ZiG Manager. 2 - Thin Client Management. 3 - Remote client configurations. 1 of 16

CONFIGURING A WEB SERVER AND TESTING WEBSPEED

See the installation page

Change Management for Rational DOORS User s Guide

System Administration Training Guide. S100 Installation and Site Management

FileMaker Server 15. Custom Web Publishing Guide

Password Reset PRO. Quick Setup Guide for Single Server or Two-Tier Installation

Web Development Frameworks

Creating a Guest Book Using WebObjects Builder

Transcription:

Chapter 1: An Overview Of Ruby Rails 1) What is Ruby on Rails?... 1-2 2) Overview of Rails Components... 1-3 3) Installing Rails... 1-5 4) A Simple Rails Application... 1-6 5) Starting the Rails Server... 1-8 6) Static Pages Within a Rails Application... 1-10 7) The Structure of a Rails Application... 1-11 8) Generating a Controller... 1-12 9) Rendering the View... 1-15 10) Adding a Static Page... 1-17 11) Dynamic Pages with Embedded Ruby... 1-20 12) Using the render Method... 1-26 13) Using the link_to Method... 1-27 1-1

What is Ruby on Rails? Ruby on Rails, often shortened to Rails or RoR, is a database-backed web application development framework written in the Ruby language. First released in 2004, it aims to increase the speed and ease of web application development. The ease of development stems from assumptions made by the creators of the framework as to what is needed by developers to get started. Ruby on Rails assumes there is a best way to do things and is designed that way, while often discouraging alternative designs. The Rails philosophy is built around the following guiding principles. DRY - Don't Repeat Yourself. Repetition of code and/or information is a bad thing. Convention Over Configuration The Rails framework makes assumptions about what needs to be done and the best way to accomplish it. This is in stark contrast to the use of configuration files in other frameworks that require one to specify every little detail. REST - Representational State Transfer REST uses these existing features of the HTTP protocol to organize applications and the resources they use. MVC - Model, View, Controller Architecture MVC isolates the business logic from the user interface and assists in the maintenance of the code by clearly defining where different types of code belong within the application. 1-2

Overview of Rails Components The Rails framework is composed of the following individual components. Action Pack Active Model Action Controller Active Record Action View Active Resource Action Dispatch Action Mailer Active Support Railties An overview of each of the above components is provided below. Action Pack This gem provides the Action Controller, Action Dispatch, and Action View components to the framework. These components provide the View and Controller parts of MVC. Action Controller This component processes incoming requests to a rails application and dispatches to an intended action. Action View Action View manages the HTML and/or XML views that are the default output of the application through the use of view templates. Action Dispatch This handles the routing of web requests and dispatches them to the application. 1-3

Overview of Rails Components Action Mailer This provides a framework for including email services within an application. Active Model This component provides an interface between the View and Controller components of the Action Pack services and Active Record (described below). It allows other Object Relationship Mapping (ORM) frameworks in place of Active Record if desired. Active Record This provides the base for the Model part of MVC within a Rails application. Active Resource Active Resource provides a framework for managing connections between business objects and RESTful services within the application. Active Support This is a collection of utility classes and used within the core Rails code and your applications. Railties Railties is the core Rails code that builds the Rails applications and connects the frameworks and plugins used within a Rails application. 1-4

Installing Rails When Ruby is installed, there are additional tools included within the installation. One such tool is the gem application, which is an interface to the RubyGems package system. RubyGems is a system for managing Ruby software libraries. Ruby code packaged in this manner is called a gem. With RubyGems, you can install the latest version of Rails and its dependencies through the following command line. gem install rails Note that the above command may require 'root' access in a Linux environment. The following command will show the version of Rails that is installed on the machine. rails -v The machines in the classroom have had a specific version of Rails installed by specifying the version to install using a command similar to the one shown below. gem install rails -v 3.2.13 Since Rails 3.1, a JavaScript runtime has been needed for development Linux. It is not needed for Mac OS X or Windows. Node.js has already been installed and added to the PATH environment variable for this course. 1-5

A Simple Rails Application The first application we will build in Rails will be a simple one. Almost all Rails applications are started the same way, through the use of the rails command. The rails program creates a skeleton application to get you started. We will start by creating a directory to place all of the Rails applications that we will be developing. The directory should be created in the user's home directory and named railsapps. $ mkdir railsapps Once the directory is created, we will change into that directory. $ cd railsapps Note that throughout the course, we will show the Linux shell/command prompt ($), although we could have shown the Windows (>) prompt just the same. From within the railsapps directory, we will enter the following command. $ rails new firstapp In a Linux environment you may be prompted to enter the user's password (assuming they are in the sudoers list). The above command creates a new Rails application called firstapp in a directory of the same name. 1-6

A Simple Rails Application There will be a lot of output displaying the name of each file or directory being created to support the application being built called Firstapp - located in a directory named firstapp. Below is a summary of the purpose of each of the files and folders that are created by default. File/Folder Purpose app/ Contains the models, views, controllers and assets config/ Configuration rules for runtime, routes, database, and more config.ru Rack configuration for Rack based middleware db/ Contains database schema and database migrations doc/ Documentation for the application Gemfile Pertains to gem dependencies needed by application Gemfile.lock Pertains to gem dependencies needed by application lib/ Extended modules for application log/ Application log files public/ Static files and compiled assets accessible to the public Rakefile Default Rake tasks README.rdoc Instruction manual for your app script/ Rails script(s) that are used to deploy and run application test/ Unit tests, fixtures, and other test apparatus tmp/ Temporary files vendor/ Third party code.gitignore Patterns for files to be ignored by Git progresses. A more in depth understanding of the files and directories listed above, as well as their purpose, will be gained as the course With an application created, we will now demonstrate how to start up the Rails server in order to access the application. 1-7

Starting the Rails Server The previous pages demonstrated how to create a new Rails application by passing the new command to the rails executable. Running just the rails executable without any command will list all of the rails commands that are available. $ rails Usage: rails COMMAND [ARGS] student@localhost:~/railsapps/firstapp The most common rails commands are: generate Generate new code (short-cut alias: "g") console Start the Rails console (short-cut alias: "c") server Start the Rails server (short-cut alias: "s") dbconsole Start a console for the database specified in config/database.yml (short-cut alias: "db") new Create a new Rails application. "rails new my_app" creates a new application called MyApp in "./my_app" In addition to those, there are: application Generate the Rails application code destroy Undo code generated with "generate" (short-cut alias: "d") benchmarker See how fast a piece of code runs profiler Get profile information from a piece of code plugin Install a plugin runner Run a piece of code in the application environment (short-cut alias: "r") All commands can be run with -h (or --help) for more information. $ We will start the Rails server by passing the rails executable the server or s command. student@localhost:~/railsapps/firstapp $ rails s => Booting WEBrick => Rails 3.2.13 application starting in development http://0.0.0.0:3000 => Call with -d to detach => Ctrl-C to shutdown server [2013-03-29 12:15:58] INFO WEBrick 1.3.1 [2013-03-29 12:15:58] INFO ruby 1.9.3 (2013-02-22) [i686-linux] [2013-03-29 12:15:58] INFO WEBrick::HTTPServer#start: pid=2096 port=3000 The WEBrick server that is launched comes prepackaged with the installation of Ruby. Alternative servers such as Mongrel or Apache could also be configured to work with Rails, if desired. 1-8

Starting the Rails Server In order to ensure that the server is up and running, we can access it via a web browser using the following URL. http://localhost:3000 Note that by default, the WEBrick server listens for connections on port 3000 rather than the standard HTTP port 80. Information pertaining to each request sent to the server can be seen in the server console as shown below. student@localhost:~/railsapps/firstapp $ rails s => Booting WEBrick => Rails 3.2.13 application starting in development on http://0.0.0.0:3000 => Call with -d to detach => Ctrl-C to shutdown server [2013-03-29 12:15:58] INFO WEBrick 1.3.1 [2013-03-29 12:15:58] INFO ruby 1.9.3 (2013-02-22) [i686-linux] [2013-03-29 12:15:58] INFO WEBrick::HTTPServer#start: pid=2096 port=3000 Started GET "/assets/rails.png" for 127.0.0.1 at 2013-03-29 12:17:33-0400 Served asset /rails.png - 200 OK (7ms) 1-9

Static Pages Within a Rails Application Recall that each Rails application created generates a skeleton working application. The directory structure of this application, as shown earlier, contains a directory named public. Rails serves any files within the public directory directly to the browser. Part of the skeleton application created is a special file within the public directory, named index.html. By convention, it acts as the home page for the application. It is special in that its use in the URL is optional. The following two URLs will present the same web page. http://localhost:3000/ http://localhost:3000/index.html The HTML file shown below can be created within the public directory of the application and accessed at the URL of: http://localhost:3000/hello.html hello.html 1. <html> 2. <head><title>hello World</title></head> 3. <body><h1>a Sample HTML Page</h1></body> 4. </html> Note that this can be done without restarting the server. By convention, the WEBrick server starts up in development mode, which does not require a restart when an application is modified. 1-10

The Structure of a Rails Application While the ability of a Rails application to return static HTML files exists, dynamically generated responses are typically a core part of any Rails application. The next directory (within a skeleton Rails application) that we will study is the app directory. Directly related to the app directory is the Model-View- Controller (MVC) pattern that Rails follows. Rails, through the use of MVC, enforces the separation between the domain or business logic from the input and presentation logic. Within a dynamic web application, a controller typically takes an incoming request, interacts with a model, and then renders the view as the response back to the browser. The three directories within the app directory pertaining directly to the MVC architecture are listed below. controllers models views Since the controller typically interacts with both the view and the model within the MVC architecture, it will be the first piece that we build into our application. The controller used by Rails is the ActionController class. An ActionController is made up of one or more actions (methods in the class). A file named routes.rb is used to link the actions of an ActionController to URLs. 1-11

Generating a Controller Rails includes a script, named generate, for generating various types of Rails components. Passing the first argument of controller to the generate script can be used to generate Rails controllers. The only other required argument is the name of the controller to be created. Optionally, additional arguments can be passed representing the actions that are to be created. We will generate a controller named StaticPages with two actions named home and guestbook. This will be done using the following command. rails generate controller StaticPages home guestbook The results can be seen below. student@localhost:~/railsapps/firstapp $ rails generate controller StaticPages home guestbook create app/controllers/static_pages_controller.rb route get "static_pages/guestbook" route get "static_pages/home" invoke erb create app/views/static_pages create app/views/static_pages/home.html.erb create app/views/static_pages/guestbook.html.erb invoke test_unit create test/functional/static_pages_controller_test.rb invoke helper create app/helpers/static_pages_helper.rb invoke test_unit create test/unit/helpers/static_pages_helper_test.rb invoke assets invoke coffee create app/assets/javascripts/static_pages.js.coffee invoke scss create app/assets/stylesheets/static_pages.css.scss $ In addition to the list of files created above, the generating of the controller updates the routes file named routes.rb. The routes.rb file is located in the config directory of the application. 1-12

Generating a Controller As shown in the routes.rb file below, each action generated results in a rule being added to the routes file. routes.rb 1. Firstapp::Application.routes.draw do 2. get "static_pages/home" 3. 4. get "static_pages/guestbook" 5. 6. # The priority is based upon order of creation: 7.. 8.. 9.. 10. end The get "static_pages/home" rule above maps requests for the URL of /static_pages/home to the home action in the StaticPagesController class. The get at the beginning of the rule indicates that the action responds to a HTTP GET request. Navigating to the mapped URL of /static_pages/home results in the following page being displayed. A similar page is available for the following URL. /static_pages/guestbook 1-13

Generating the Controller Before looking at the generated HTML pages, we will look at the StaticPagesController class that was generated earlier via the following command. rails generate controller StaticPages home guestbook The controller can be found at the following location within the application directory. app/controllers/static_pages_controller.rb static_pages_controller.rb 1. class StaticPagesController < ApplicationController 2. def home 3. end 4. 5. def guestbook 6. end 7. end The ApplicationController class, from which StaticPagesController inherits, is defined in another generated file in the same directory named application_controller.rb application_controller.rb 1. class ApplicationController < ActionController::Base 2. protect_from_forgery 3. end The default behavior for all action controllers is typically declared in the ApplicationController class that all action controllers inherit from. The home and guestbook actions generated when the StaticPagesController was generated are initially empty. 1-14

Rendering the View Recall that many files were created with the following command. So far, we have looked at the following generated files. app/config/routes.rb rails generate controller StaticPages home guestbook app/controllers/static_pages_controller.rb app/controllers/application_controller.rb When actions are supplied to the rails generate controller script, such as the home and guestbook actions above, the script also creates a view (the View part of MVC) for each action. The views created for the home and guestbook actions are: app/views/static_pages/home.html.erb app/views/static_pages/guestbook.html.erb The.erb (embedded Ruby) extension indicates that the file may contain embedded Ruby code. The.html in the file name indicates that the file contains HTML. The generated.html.erb files listed above do not yet have any embedded Ruby code in them. They are simply snippets of HTML code that can be seen on the following page. 1-15

Rendering the View home.html.erb 1. <h1>staticpages#home</h1> 2. <p>find me in app/views/static_pages/home.html.erb</p> 1. <h1>staticpages#guestbook</h1> guestbook.html.erb 2. <p>find me in app/views/static_pages/guestbook.html.erb</p> The actual view rendered to the user for each action is created by combining the code in the above views into another file that controls the overall layout of both of the views. The name of the file, acting as a template for the layout of the actions' views, can be found at the following location. app/views/layouts/application.html.erb application.html.erb 1. <!DOCTYPE html> 2. <html> 3. <head> 4. <title>firstapp</title> 5. <%= stylesheet_link_tag "application", 6. :media => "all" %> 7. <%= javascript_include_tag "application" %> 8. <%= csrf_meta_tags %> 9. </head> 10. <body> 11. <%= yield %> 12. </body> 13. </html> The embedded Ruby is all of the code above between the <%= %> tags and will be discussed in more detail shortly. 1-16

Adding a Static Page The previous pages have concentrated on many of the files that are automatically generated by the generate controller command. We will now concentrate on how to manually add an additional page to the existing application named Firstapp. The page we will create will be associated with an action named info. We will model this around the structure that was created for the previous home and guestbook actions. Adhering to the standard Rails naming conventions will be an important part in the new additions working properly. Accomplishing this requires a minimum of three things. Add a route to the routes file for the action. Add the action to the StaticPagesController. Create a corresponding view for the action. The first step to creating the new page is to update the routes.rb file, as shown below. routes.rb 1. Firstapp::Application.routes.draw do 2. get "static_pages/home" 3. get "static_pages/guestbook" 4. 5. get "static_pages/info" 6.. 7.. 8.. 9. end The line above, in bold, maps the URL of static_pages/info to the info action in the controller. 1-17

Adding a Static Page Attempting to access the newly mapped URL will result in the following page being displayed. The above indicates that the action (method) named info has not been defined yet inside of the controller. The second step is to add the missing info action to the controller as shown below. static_pages_controller.rb 1. class StaticPagesController < ApplicationController 2. def home 3. end 4. 5. def guestbook 6. end 7. 8. def info 9. end 10. end Attempting to access the URL will now result in a different error being displayed, as shown on the next page. 1-18

Adding a Static Page The last step to creating a new static page will be to define the view (template) to avoid the above error. The name of the file that needs to be created, in order to act as the view, will be info.html.erb. It is shown below. info.html.erb 1. <h1>staticpages#info</h1> 2. Find me in: 3. <code>app/views/static_pages/info.html.erb</code> 4. <p>feel free to add any other 5. information to this page</p> The view that that the controller will present is displayed below. 1-19

Dynamic Pages with Embedded Ruby The Firstapp application that has been created consists of the three actions with the following three views. app/views/static_pages/guestbook.html.erb app/views/static_pages/home.html.erb app/views/static_pages/info.html.erb While the above views are permitted to have embedded Ruby in them, they currently contain only static HTML. Recall that all of the views rely on the following template for the layout of each view. app/views/layouts/application.html.erb application.html.erb 1. <!DOCTYPE html> 2. <html> 3. <head> 4. <title>firstapp</title> 5. <%= stylesheet_link_tag "application", 6. :media => "all" %> 7. <%= javascript_include_tag "application" %> 8. <%= csrf_meta_tags %> 9. </head> 10. <body> 11. <%= yield %> 12. </body> 13. </html> This file contains special tags where the Ruby code inside of them results in dynamic output generated in the view. The purpose of the template is to rely on the DRY principle mentioned earlier where you Don't Repeat Yourself. 1-20

Dynamic Pages with Embedded Ruby Most, if not all, browsers provide a way of viewing the page source that the browser receives to render the view. Below is the result of viewing the source of the info view through the browser. Each set of <%= => tags within application.html.erb results in dynamic output that is sent to the browser. For instance the following tag: <%= javascript_include_tag "application" %> <script src="/assets/jquery_ujs.js?body=1"... <script src="/assets/static_pages.js?body=1"... <script src="/assets/application.js?body=1"... results in the following script tags being sent to the browser. <script src="/assets/jquery.js?body=1"... 1-21

Dynamic Pages with Embedded Ruby For each of the views, anything that is similar to all of them can be placed within the application.html.erb file. The parts of the view that are specific to each are then placed in their respective.erb files. When working with embedded Ruby, two special tags can be used to surround the Ruby code that will then be executed to generate dynamic content. <%= %> This is typically referred to as output embedding tags. Use of this tag results in the Ruby expression inside of the tag being evaluated and inserted into the HTML stream. <% %> This is typically referred to as regular embedding tags. Use of this tag will evaluate all of the Ruby code inside of the tag but nothing is inserted into the HTML stream. We will modify the info view to include several of the embedded Ruby tags to include some dynamic output. The changes will be as follows. Use regular embedding tags to initialize some variables. Use output embedding tags to output the variables. Use output embedding tags to output a Ruby object. The modified info view is shown on the next page. 1-22

Dynamic Pages with Embedded Ruby info.html.erb 1. <h1>staticpages#info</h1> 2. Find me in: 3. <code>app/views/static_pages/info.html.erb</code> 4. <% x = 10 5. y = 20 6. z = x + y 7. lucky_number = rand(100) 8. %> 9. <div>x = <%= x %></div> 10. <div>y = <%= y %></div> 11. <div>x + y = <%= z %></div> 12. <hr /> 13. <div>your lucky number is: 14. <%= lucky_number %></div> 15. <hr /> 16. Today is: <%=Time.now.to_s %><br /> 17. Today is: <%=Time.now %><br /> The updated info view looks like the following in the browser. Refreshing the page should produce different values since the page is being generated dynamically. 1-23

Dynamic Pages with Embedded Ruby All three views currently have an <h1> tag defined at the top whose data is similar to all three views. The technique we will use to get rid of the repetitiveness between the pages will involve creating Ruby instance variables within the actions of the controller. Since the variable part of the <h1> tag is the name of the view, we will set the value of an instance variable we will call @view_name to the appropriate value for each action. This @view_name instance variable can then be accessed within the embedded Ruby tag to output its value. The end result will be an <h1> tag identical within all three views. Therefore we will instead move it to the layout file that is common to all three views. The modified version of the controller is shown below where the code that has been added is shown in bold. static_pages_controller.rb 1. class StaticPagesController < ApplicationController 2. def home 3. @view_name = "home" 4. end 5. 6. def guestbook 7. @view_name = "guestbook" 8. end 9. 10. def info 11. @view_name = "info" 12. end 13. end With the @view_name instance variable defined, the modified layout file that will use the variable in an embedded ruby tag is shown on the next page. 1-24

Dynamic Pages with Embedded Ruby application.html.erb 1. <!DOCTYPE html> 2. <html> 3. <head> 4. <title>firstapp</title> 5. <%= stylesheet_link_tag "application", 6. :media => "all" %> 7. <%= javascript_include_tag "application" %> 8. <%= csrf_meta_tags %> 9. </head> 10. <body> 11. <h1>staticpages#<%= @view_name %></h1> 12. <%= yield %> 13. 14. </body> 15. </html> Since the <h1> tag and its dynamic content is now defined within the template, the corresponding <h1> tag in each of the views can now be removed. This can be seen in the modified home.html.erb view shown below. home.html.erb 1. <p>find me in app/views/static_pages/home.html.erb</p> 1-25

Using the render Method The default behavior of each of the actions defined in a controller is to render a view whose name corresponds to that of the action. i.e., the info action rendering the info.html.erb view. The render method of the controller, inherited from ActionController::Base, can be used to render a view that is associated with a different action, if desired. There are three variations on the Ruby syntax that can be used to accomplish this inside one of your actions. In the variations below, name_of_an_action should be replaced with the actual name of an action such as info, guestbook, or home in the current application. The first variation passes a string to the render method. render "name_of_an_action" The second variation passes a symbol. render :name_of_an_action The last variation passes a hash to the render method. This is from Rails 2 but is no longer required in Rails 3. render :action => "name_of_an_action" So, if the info method were to be defined as follows: def info render :guestbook end The info action would render the guestbook.html.erb view rather than the default of info.html.erb. 1-26

Using the link_to Method The link_to method allows easy navigation to URLs. The URLs generated by the method may be to views within the application or URLs outside of the application. The link_to method takes a variable number of arguments (and as such there are several variations on how the method can be used). The first argument should be a string representing the text to display for the link that will be created. The second argument is the URL to link to, and can either be a string representing the URL to use, or a literal hash of the action/value pair. Subsequent arguments are a hash of attributes and values that are added to the generated link. Several examples of using the link_to method within embedded Ruby and the resulting tag that is generated are shown below. <%= link_to "Info", {:action => "info"} %> generates the following link: <a href="/static_pages/info">info</a> <%= link_to "Info", "info" %> generates the following link: <a href="info">info</a> <%= link_to "/training/etc", "http://trainingetc.com", :class => "links" %> generates the following link: <a href="http://trainingetc.com" class="links">/training/etc</a> 1-27

Using the link_to Method A modified version of the home view is shown below. The examples of the link_to method from the previous page and some additional examples have been included. home.html.erb 1. <p>find me in 2. app/views/static_pages/home.html.erb</p> 3. <h3>links passing action name as a hash<h3> 4. <%= link_to "Info", {:action => "info"} %> 5. <%= link_to "GuestBook", {:action => "guestbook"} %> 6. <hr> 7. <h3>links passing a relative URL as a string<h3> 8. <%= link_to "Info", "info" %> 9. <%= link_to "GuestBook", "guestbook" %> 10. <hr> 11. <h3>link passing an absolute URL as string<h3> 12. <%= link_to "/training/etc", 13. "http://trainingetc.com" %> 14. <%= link_to "/training/etc", 15. "http://trainingetc.com", :class => "links" %> 1-28

Exercises 1. You are going to mimic most of the things we have done in this chapter. Create a Rails application named Store. Create a controller named Inventory with index, buy, and sell actions. Recall that passing the actions as parameters when the controller is being generated will also create the associated views/templates. Start the Rails server. Test each of the following URLs. http://localhost:3000 http://localhost:3000/inventory/index http://localhost:3000/inventory/buy http://localhost:3000/inventory/sell Modify the index action to generate a random number between 0 and 99. Now, use the render method to render either the buy or sell view, depending upon whether the random number is greater than 50. In either case, include the random number within the view. Now, place a link in both the buy and sell views permitting a user to easily navigate back to the index view. 1-29

This Page Intentionally Left Blank 1-30