Your SlideShare is downloading. ×
Upcoming SlideShare
Loading in...5

Thanks for flagging this SlideShare!

Oops! An error has occurred.

Saving this for later? Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime – even offline.
Text the download link to your phone
Standard text messaging rates apply



Published on

  • Be the first to comment

  • Be the first to like this

No Downloads
Total Views
On Slideshare
From Embeds
Number of Embeds
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

No notes for slide


  • 1. 24
    • Ruby on Rails
  • 2.
    • 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
  • 3.
    • 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
    • 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 library to add visual effects to your programs.
  • 5.
    • 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
    • 24.8 Wrap-Up
    • 24.9 Web Resources
  • 6. 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.
  • 7. 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.
  • 8. Fig. 24.1 | Instant Rails application running.
  • 9. 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.
  • 10. Outline welcome.rb The puts command writes a line of text to the console
  • 11. Fig. 24.3 | Launching the Ruby Interpreter in Instant Rails.
  • 12. Fig. 24.4 | Using the Ruby interpreter to run a simple Ruby script.
  • 13. Fig. 24.5 | Using Interactive Ruby to execute Ruby statements.
  • 14. 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
  • 15. Outline types.rb (2 of 2) The capitalize method capitalizes the first letter of a string
  • 16. 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
  • 17. 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
  • 18. 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
  • 19. Outline Classes.rb (2 of 2) Create an instance using the class name and new , supplying any arguments required by the constructor
  • 20. 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.
  • 21. Fig. 24.10 | Model-View-Controller architecture.
  • 22. Fig. 24.11 | Rails directory structure for a new Rails application.
  • 23. 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 .
  • 24. Outline app/controllers/ welcome_ controller.rb Call the render method, specifying its parameter using the text symbol
  • 25. Fig. 24.13 | Starting the Mongrel web server.
  • 26. Outline app/controllers/ welcome_ controller.rb Define a class variable in the controller that contains information about the server
  • 27. Outline app/views/welcome/hello.rhtml The view has access to the controller’s class variables
  • 28. 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
  • 29. Fig. 24.17 | Creating a model in the Ruby Console.
  • 30. 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.
  • 31. 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.
  • 32. 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
  • 33. 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.
  • 34. Outline employee.rb
  • 35. 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
  • 36. Fig. 24.21 | View of the new action when generated by the scaffold.
  • 37. 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
  • 38. 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.
  • 39. Outline db/migrate/001_ create_users.rb Create a database table to store users Create a test user
  • 40. 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.
  • 41. Outline app/models/user .rb
  • 42. 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
  • 43. 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.
  • 44. 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
  • 45. Outline app/views/ layouts/users .rhtml
  • 46. Outline db/migrate/002_ create_messages .rb
  • 47. 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
  • 48. Outline db/migrate/003_ create_forums.rb
  • 49. 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
  • 50. 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
  • 51. 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
  • 52. Outline app/views/forums/list.rhtml (1 of 2) Use the @forums array (defined in the controller) to create a list of all
  • 53. Outline app/views/forums/list.rhtml (2 of 2)
  • 54. 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
  • 55. Outline app/views/forums/_form.rhtml
  • 56. Outline app/views/forums/delete.rhtml Use the collection_select method to generate a drop-down menu from the @forms array.
  • 57. Outline app/views/layouts/forums.rhtml (1 to 2)
  • 58. Outline app/views/layouts/forums.rhtml (2 to 2) Link to the admin action to allow the user to login
  • 59. 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
  • 60. Outline app/controllers/ messages_ controller.rb (2 to 2)
  • 61. 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’]
  • 62. Outline app/views/ messages/list .rhtml (2 to 2)
  • 63. Outline app/views/ messages/_form .rhtml (1 to 2) The text_area method generates a textarea XHTML element
  • 64. Outline app/views/ messages/_form .rhtml (2 to 2)
  • 65. 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/
  • 66. Outline app/views/ layouts/forums .rhtml (1 to 2) Include the default JavaScript libraries, including and Prototype
  • 67. Outline app/views/ layouts/forums .rhtml (2 to 2)
  • 68. 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
  • 69. Outline app/views/forums/list.rhtml (2 to 2)
  • 70. 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
  • 71. Outline app/views/ messages/list .rhtml (2 to 2)
  • 72. 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
  • 73. Outline app/views/ messages/new .rhtml (2 to 2)
  • 74. 24.7
    • 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 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.
    • also provides the text_field_with_auto_complete method, which enables server-side autocompletion of a text field.
  • 75. Fig. 24.46 |’s Fade effect.
  • 76. Outline app/views/ scriptaculous_ demo/index.rhtml Play a Shrink effect on the image div before proceeding to the playEffect action
  • 77. Outline app/controllers/ scriptaculous_ demo_controller .rb
  • 78. Outline app/views/layouts /application .rhtml
  • 79. Outline app/views/ scriptaculous_ demo/_link.rhtml (1 to 5)
  • 80. Outline app/views/ scriptaculous_ demo/_link.rhtml (2 to 5)
  • 81. Outline app/views/ scriptaculous_ demo/_link.rhtml (3 to 5)
  • 82. Outline app/views/ scriptaculous_ demo/_link.rhtml (4 to 5)
  • 83. Outline app/views/ scriptaculous_ demo/_link.rhtml (5 to 5)
  • 84. Fig. 24.51 | Flickr Photo Viewer showing search results for bugs .
  • 85. Outline app/view/ flickr/index .rhtml (1 to 2) A form that searches for tags, using blind effects and a loading indicator
  • 86. Outline app/view/ flickr/index .rhtml (2 to 2)
  • 87. Outline app/controllers/ flickr_ controller.rb Search for tags and display paginated results
  • 88. Outline app/views/flickr/_thumbs.rhtml Display a thumbnail that links to the full sized image
  • 89. Outline app/views/flickr/fullsizeImage .rhtml Display the full size version of an image