iw3htp4_24-FINAL.ppt
Upcoming SlideShare
Loading in...5
×
 

iw3htp4_24-FINAL.ppt

on

  • 1,545 views

 

Statistics

Views

Total Views
1,545
Views on SlideShare
1,545
Embed Views
0

Actions

Likes
0
Downloads
6
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

iw3htp4_24-FINAL.ppt iw3htp4_24-FINAL.ppt Presentation Transcript

  • 24
    • Ruby on Rails
    • Convention is the ruler of all.
      • Pindar
    • Where the telescope ends, the microscope begins. Which of the two has the grander view?
      • Victor Hugo
    • … We grow more partial for the observer’s sake.
      • Alexander Pope
    • Those who cannot remember the past are condemned to repeat it.
      • George Santayana
    • Let’s look at the record.
      • Alfred Emanuel Smith
    • All that matters is that the miraculous become the norm.
      • Henry Miller
  • OBJECTIVES
    • In this chapter you will learn:
    • Basic Ruby programming.
    • How to use the Rails framework.
    • The Model-View-Controller paradigm.
    • How to use ActiveRecord to model a database.
    • How to construct web applications that interact with a database.
    • How to create a web-based message forum.
    • How to develop Ajax-enabled applications in Ruby on Rails.
    • How to use the built-in Script.aculo.us library to add visual effects to your programs.
    • 24.1 Introduction
    • 24.2 Ruby
    • 24.3 Rails Framework
    • 24.4 ActionController and ActionView
    • 24.5 A Database-Driven Web Application
    • 24.6 Case Study: Message Forum
    • 24.6.1 Logging In and Logging Out
    • 24.6.2 Embellishing the Models
    • 24.6.3 Generating Scaffold Code
    • 24.6.4 Forum Controller and Forum Views
    • 24.6.5 Message Controller and Message Views
    • 24.6.6 Ajax-Enabled Rails Applications
    • 24.7 Script.aculo.us
    • 24.8 Wrap-Up
    • 24.9 Web Resources
  • 24.1 Introduction
    • Ruby on Rails (also known as RoR or just Rails) is a framework for developing data-driven web applications.
    • A web framework is a set of libraries and useful tool that can be used to build dynamic web applications.
    • Ruby on Rails is different from most other programming languages because it takes advantage of many conventions to reduce development time. If you follow these conventions, the Rails framework generates substantial functionality and perform many tasks for you.
    • Ruby on Rails has built-in libraries for performing common web development tasks, such as interacting with a database, sending mass e-mails to clients or generating web services.
    • Rails has built-in libraries that provide Ajax functionality, improving the user experience. Rails is quickly becoming a popular environment for web development.
    • Ruby on Rails was created by David Heinemeier Hansson of the company 37Signals.
  • 24.2 Ruby
    • The Ruby scripting language was developed by Yukihiro “Matz” Matsumoto in 1995 to be a flexible, object-oriented scripting language.
    • Ruby’s syntax and conventions are intuitive—they attempt to mimic the way a developer thinks. Ruby is an interpreted language.
    • Instant Rails is a stand-alone Rails development and testing environment that includes Ruby, Rails, MySQL, Apache, PHP and other components necessary to create and run Rails applications.
    • If you are using Mac OS X, there is an application similar to Instant Rails called Locomotive.
    • The method puts prints the text to the terminal, followed by a newline.
    • A method can have parentheses surrounding its parameters, but this is not typical in Ruby unless they are used to avoid ambiguity.
    • A line of Ruby code does not have to end with a semicolon, although one can be placed there.
    • One way to run a Ruby script is to use the Ruby interpreter.
    • IRB (Interactive Ruby) can be used to interpret Ruby code statement by statement.
  • Fig. 24.1 | Instant Rails application running.
  • 24.2 Ruby (Cont.)
    • Ruby uses dynamic typing, which allows changes to a variable’s type at execution time.
    • Everything is an object in Ruby, so you can call methods on any piece of data.
    • Hash Object s are mapped to other Object s in key/value pairs.
    • The exclamation point after a method name is a Ruby convention indicating that the object on which the method is called will be modified.
    • Ruby has support for code blocks—groupings of Ruby statements that can be passed to a method as an argument.
    • The initialize method acts like a constructor in other object-oriented languages—it is used to declare and initialize an object’s data.
    • When each instance of a class maintains its own copy of a variable, the variable is known as an instance variable and is declared in Ruby using the @ symbol.
    • Classes can also have class variables, declared using the @@ symbol, that are shared by all copies of a class.
    • When an object is concatenated with a string, the object’s to_s method is called to convert the object to its string representation.
  • Outline welcome.rb The puts command writes a line of text to the console
  • Fig. 24.3 | Launching the Ruby Interpreter in Instant Rails.
  • Fig. 24.4 | Using the Ruby interpreter to run a simple Ruby script.
  • Fig. 24.5 | Using Interactive Ruby to execute Ruby statements.
  • Outline types.rb (1 of 2) Ruby uses = as the assignment operator Enclosing a variable in curly braces ( {} )preceded by a pound sign ( # ) causes it to be interpolated You can call the round method on any variable of type Fixnum Ruby variables are dynamically typed, so variables have no explicit type, but can hold any type of data at any time
  • Outline types.rb (2 of 2) The capitalize method capitalizes the first letter of a string
  • Outline arraysAndHashes .rb Arrays can be created using comma-separated lists in square brackets The length of an array is stored in its length property Elements are accessed using square bracket notation; You can also access items starting from the end of the array using negative indices You can create a hash, which stores key-value pairs, by separating keys from values with the => operator and enclosing the list in curly braces
  • Outline Control Statements.rb Methods are defined using the def keyword, and method definitions end with the end keyword The each method can be used on arrays to iterate through their elements. The parameters of a code block are placed between pipe characters ( || )at the beginning of the block
  • Outline Classes.rb (1 of 2) Classes are defined beginning with the class keyword and ending with the end keyword Class variables are preceded by @@ Instance variables are preceded by @ Every class has a to_s method that returns a string representation of the object. This class overrides its to_s method Create a constructor by defining an initialize method
  • Outline Classes.rb (2 of 2) Create an instance using the class name and new , supplying any arguments required by the constructor
  • 24.3 Rails Framework
    • While users have benefitted from the rise of database-driven web applications, web developers have had to implement rich functionality with technology that was not designed for this purpose.
    • The Rails framework combines the simplicity of development that has become associated with Ruby with the ability to rapidly develop database-driven web applications.
    • Ruby on Rails is built on the philosophy of convention over configuration—if you follow certain programming idioms, your applications will require little or no configuration and Rails will generate substantial portions of the applications for you.
    • The Model-View-Controller (MVC) architectural pattern separates application data (contained in the model) from graphical presentation components (the view) and input-processing logic (the controller).
    • ActiveRecord is used to map a database table to an object.
    • ActionView is a set of helper methods to modify user interfaces.
    • ActionController is a set of helper methods to create controllers.
  • Fig. 24.10 | Model-View-Controller architecture.
  • Fig. 24.11 | Rails directory structure for a new Rails application.
  • 24.4 ActionController and ActionView
    • Ruby on Rails has two classes, ActionController and ActionView , that work together to process a client request and render a view.
    • To generate a controller in Rails, you can use the built-in Controller generator by typing ruby script/generate controller name .
    • A Ruby on Rails application must be run from a web server
    • Instant Rails comes with a built-in web server named Mongrel, which is easy to use to test Rails applications on the local machine.
    • When generating output, a controller usually renders a template—an XHTML document with embedded Ruby that has the .rhtml filename extension.
    • The request object contains the environment variables and other information for a web page.
    • Erb (embedded Ruby) that is located between the <%= %> tags in rhtml files is parsed as Ruby code and formatted as text.
    • A set of Ruby tags without an equals sign— <% %> —represents statements to execute as Ruby code but not formatted as text.
    • Rails allows you to add headers and footers with a layout—a master view that is displayed by every method in a controller.
    • A layout can generate a template for a specific method using yield .
  • Outline app/controllers/ welcome_ controller.rb Call the render method, specifying its parameter using the text symbol
  • Fig. 24.13 | Starting the Mongrel web server.
  • Outline app/controllers/ welcome_ controller.rb Define a class variable in the controller that contains information about the server
  • Outline app/views/welcome/hello.rhtml The view has access to the controller’s class variables
  • Outline app/views/layouts/welcome.rhtml A controller’s action_name method displays the action that is currently being called The layout yields to the view associated with the current action
  • Fig. 24.17 | Creating a model in the Ruby Console.
  • 24.5 A Database-Driven Web Application
    • Rails makes extensive use of Object-Relational Mapping (ORM) that maps a database to application objects.
    • The objects that Rails uses to encapsulate a database inherit from ActiveRecord .
    • One ActiveRecord convention is that every model that extends ActiveRecord::Base in an application represents a table in a database.
    • By convention, the table that the model represents has a name which is the lowercase, pluralized form of the model’s name.
    • Rails uses a generator to create the Employee model. You use a generator by typing ruby script/generate model employee in the Ruby Console, after navigating to your application directory.
  • 24.5 A Database-Driven Web Application (Cont.)
    • The ActiveRecord object has a special feature called Migration , which allows you to perform database operations within Rails.
    • ActiveRecord has built-in functionality for many create, retrieve, update and destroy methods known in Rails as CRUD.
    • We can execute the migration using Ruby’s rake command by typing rake db:migrate , which will call the self.up method of all the migrations located in your db/migrate directory.
    • If you ever want to roll back the migrations, you can type rake db:migrate VERSION=0 , which calls each migration’s self.down method.
    • The scaffold method is a powerful tool that automatically creates CRUD functionality. It creates methods such as new , edit and list so you don’t have to create them yourself.
  • Outline db/migrate/001_ create_employees.rb The up method in a migration does the work on the database The down method undoes what the up method did so that you can roll changes forward and back We create a table in the database with three columns containing strings Create three entries in the table, specifying values for each field To undo the changes, we simply drop the table
  • Common Programming Error 24.1
    • If the code that comes after the creation of the table in the self.up is erroneous, the migration will fail, and will not be able to execute again because the table will already exist. Also, Rails will not have marked the migration as successfully completed, so the version will still be 0 and the migration cannot be rolled back. One way to prevent this problem is to force the table to be dropped every time before creating it. Another solution is splitting up the migration into smaller discrete migrations, one to create the table and another to insert data in the table.
  • Outline employee.rb
  • Outline app/controllers/employees_controller.rb The scaffold method dynamically generates any CRUD methods that are not already defined in the controller Our list method (called when the list action is invoked) creates an array of all employees so that the view can display them
  • Fig. 24.21 | View of the new action when generated by the scaffold.
  • Outline app/views/ employees/list .rhtml Loop through each employee in the database Access each employee’s first and last name as properties of the current employee object
  • 24.6 Case Study: Message Form
    • Validators that will be called when the database is modified, can be applied to an object that inherits from ActiveRecord .
    • The method validates_presence_of ensures that all the fields specified by its parameters are not empty.
    • The method validates_format_of matches all the fields specified by its parameters with a regular expression.
    • The link_to method is used to link to an action in the controller and pass arguments to it.
    • A partial is a block of HTML and embedded Ruby code stored in another file and inserted directly into the document.
    • Rails includes a JavaScript library called Prototype that contains easy-to-use cross-browser Ajax functions.
    • The javascript_include_tag helper method is used to link in JavaScript libraries.
    • The link_to_remote method allows us to link to JavaScript that we included in the layout file.
    • Specifying the url and update parameters inside the link_to_remote method tells Rails to convert these tags into prototype Ajax.Updater objects that will update the page asynchronously.
  • Outline db/migrate/001_ create_users.rb Create a database table to store users Create a test user
  • Common Programming Error 24.2
    • Creating a column without explicitly specifying a limit on length will cause Rails to truncate the data entered into the database with database-defined limits.
  • Outline app/models/user .rb
  • Outline app/controllers/ users_controller.rb The admin action creates a new User The validate action implements a login attempt If the login is successful, store the User object in a session variable
  • Performance Tip 24.1
    • Storing full objects in the session is inefficient. The user object is one of the rare exceptions, because it doesn’t change very often and is frequently needed in web applications that manage the state information for unique clients.
  • Outline app/views/users/ admin.rhtml The login form submits to the validate action, where the login information is processed Both fields specify a model and a column to which they correspond
  • Outline app/views/ layouts/users .rhtml
  • Outline db/migrate/002_ create_messages .rb
  • Outline app/models/ message.rb Specify that each Message belongs to a Forum Validators make sure that a Message is not created unless the title , author , email , and message are defined, and the email is properly formatted
  • Outline db/migrate/003_ create_forums.rb
  • Outline app/models/forum.rb A forum model is a container for multiple message objects When a forum is destroyed, all of its messages are destroyed with it
  • Outline app/controllers/ forums_ controller.rb (1 of 2) Ensure that anything modifying the database is sent to the server as a POST request Go back to the list page once a change has been submitted Use flash to display an error at the top of the page if the user is not logged in
  • Outline app/controllers/ forums_ controller.rb (2 of 2) Notify the user that their action was successful Only allow the user to see a list of forums to delete if the user is an administrator Delete a forum and redirect to the list page
  • Outline app/views/forums/list.rhtml (1 of 2) Use the @forums array (defined in the controller) to create a list of all
  • Outline app/views/forums/list.rhtml (2 of 2)
  • Outline app/views/forums/new.rhtml The render :partial method inserts the contents of a partial file (in this case _form.rhtml ) into a document
  • Outline app/views/forums/_form.rhtml
  • Outline app/views/forums/delete.rhtml Use the collection_select method to generate a drop-down menu from the @forms array.
  • Outline app/views/layouts/forums.rhtml (1 to 2)
  • Outline app/views/layouts/forums.rhtml (2 to 2) Link to the admin action to allow the user to login
  • Outline app/controllers/ messages_ controller.rb (1 to 2) Get an array of messages belonging to the forum with the forum_id stored in the session object for the list action
  • Outline app/controllers/ messages_ controller.rb (2 to 2)
  • Outline app/views/ messages/list .rhtml (1 to 2) Format the creation time using the strftime method of the Time object stored in message[‘created_on’]
  • Outline app/views/ messages/list .rhtml (2 to 2)
  • Outline app/views/ messages/_form .rhtml (1 to 2) The text_area method generates a textarea XHTML element
  • Outline app/views/ messages/_form .rhtml (2 to 2)
  • Outline app/views/ layouts/messages.rhtml The stylesheet_link_tag generates a link element to an external style sheet—in this case, scaffold.css —in public/stylesheets/
  • Outline app/views/ layouts/forums .rhtml (1 to 2) Include the default JavaScript libraries, including Script.aculo.us and Prototype
  • Outline app/views/ layouts/forums .rhtml (2 to 2)
  • Outline app/views/forums/list.rhtml (1 to 2) The link to each forum makes an Ajax call, displaying the selected forum’s messages in the currentForum div using a partial page update Messages are displayed in this div
  • Outline app/views/forums/list.rhtml (2 to 2)
  • Outline app/views/ messages/list .rhtml (1 to 2) The New Message link puts the form in on the same page using a partial page update
  • Outline app/views/ messages/list .rhtml (2 to 2)
  • Outline app/views/ messages/new .rhtml (1 to 2) Forum creation is also done without reloading the entire page Canceling forum creation replaces the form with the list of forums
  • Outline app/views/ messages/new .rhtml (2 to 2)
  • 24.7 Script.aculo.us
    • Script.aculo.us allows you to easily create visual effects similar to those in Adobe Flash and Microsoft Silverlight.
    • The library provides many pre-defined effects, as well as the ability to create your own effects from the pre-defined ones.
    • The Script.aculo.us library also provides drag-and-drop capability through the draggable_element and drop_receiving_element methods.
    • The sortable_element method allows you to describe a list that allows the user to drag and drop list items to reorder them.
    • Script.aculo.us also provides the text_field_with_auto_complete method, which enables server-side autocompletion of a text field.
  • Fig. 24.46 | Script.aculo.us’s Fade effect.
  • Outline app/views/ scriptaculous_ demo/index.rhtml Play a Shrink effect on the image div before proceeding to the playEffect action
  • Outline app/controllers/ scriptaculous_ demo_controller .rb
  • Outline app/views/layouts /application .rhtml
  • Outline app/views/ scriptaculous_ demo/_link.rhtml (1 to 5)
  • Outline app/views/ scriptaculous_ demo/_link.rhtml (2 to 5)
  • Outline app/views/ scriptaculous_ demo/_link.rhtml (3 to 5)
  • Outline app/views/ scriptaculous_ demo/_link.rhtml (4 to 5)
  • Outline app/views/ scriptaculous_ demo/_link.rhtml (5 to 5)
  • Fig. 24.51 | Flickr Photo Viewer showing search results for bugs .
  • Outline app/view/ flickr/index .rhtml (1 to 2) A form that searches for tags, using blind effects and a loading indicator
  • Outline app/view/ flickr/index .rhtml (2 to 2)
  • Outline app/controllers/ flickr_ controller.rb Search for tags and display paginated results
  • Outline app/views/flickr/_thumbs.rhtml Display a thumbnail that links to the full sized image
  • Outline app/views/flickr/fullsizeImage .rhtml Display the full size version of an image