Building Dynamic Web 2.0 Websites with Ruby on Rails - Rajshekhar A P - E-Book

Building Dynamic Web 2.0 Websites with Ruby on Rails E-Book

Rajshekhar A P

0,0
19,16 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

In Detail

Ruby on Rails is an open-source web application framework ideally suited to building business applications; accelerating and simplifying the creation of database-driven websites. Often shortened to Rails or RoR, it provides a stack of tools to rapidly build web applications based on the Model-View-Controller design pattern.
 
This book is a tutorial for creating a complete website with Ruby on Rails. It will teach you to develop database-backed web applications according to the Model-View-Controller pattern. It will take you on a joy ride right from installation to a complete dynamic website. All the applications discussed in this book will help you add exciting features to your website. This book will show you how to assemble RoR's features and leverage its power to design, develop, and deploy a fully featured website. Each chapter adds a new feature to the site, adding new knowledge, skills, and techniques.

Learn to create dynamic websites with Ruby on Rails.

Approach

This book is a practical guide to creating a complete Web 2.0 website with Ruby on Rails. In this book, each chapter adds a new feature to the site, adding new knowledge, skills, and techniques. You will learn about the features of RoR by adding those features to your website. You will also learn about Software Development Life Cycle (SDLC) as each chapter closely follows the SDLC starting from requirement gathering and ending with testing.

Who this book is for

This book is for anyone who has basic concepts of object-oriented programming as well as relational databases and wants to develop online applications using Ruby on Rails. Prior knowledge of Ruby or Rails is not expected.

Sie lesen das E-Book in den Legimi-Apps auf:

Android
iOS
von Legimi
zertifizierten E-Readern

Seitenzahl: 225

Veröffentlichungsjahr: 2008

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Table of Contents

Building Dynamic Web 2.0 Websites with Ruby on Rails
Credits
About the Author
About the Reviewer
Preface
What This Book Covers
What You Need for This Book
Conventions
Reader Feedback
Customer Support
Downloading the Example Code for the Book
Errata
Questions
1. Getting Started with Ruby and RoR
Ruby and RoR—The Next Level in Dynamic Web Development
Ruby
Ruby on Rails (RoR)
Philosophy
Features
Installing and Configuring Ruby and RoR
Manual Installation
Downloading and Installing Ruby
Updating Gem
Installing RoR
One-Click RoR Installation
Download and Unzip the Instant Rails
Configure Instant Rails Installation
Testing the Installation
Ruby
RoR
Summary
2. Getting to Know Ruby and RoR
Ruby—the Basics
Classes, Attributes, Methods, and Objects
Classes
Attributes
Methods
Objects
Inheritance
Modules
Data Types
Number
Float
String
Blocks and Iterators
Blocks
Iterators
Exception Handling
Data Structures
Arrays
Hashes
RoR—Concepts and Components
RoR is a Ruby-Based Framework
RoR Implements MVC Pattern
Active Record
Action View
Action Controller
Hello World—the RoR Way
Setting up the Application Structure
Adding the First Controller Class
Defining the Action Method
Adding the View Template
Testing the Application
Summary
3. TaleWiki—The Basic Setup
Understanding the Requirements
System Requirements
Module-Specific Requirements
Managing the Stories
Designing the Database
Understanding the Conventions
Designing the E-R Model
Defining the Schema
Creating the Tables
TaleWiki—Developing the Tale Management Module
Creating the Application Structure
Generating the Scaffolds
Customizing the Model
Relationship Mapping
Data Validation
Customizing the Controller
Refining the View
Refining the New Tale Template
Refining the Edit Tale Template
Testing the Application
Summary
4. Managing the Users
Understanding the Requirements
Managing the User
Managing Roles
Designing the Tables
Designing the E-R Model
Deriving the Schema
Creating the Tables
Developing the User Management
Developing the Role Management
Generating the Scaffolds
Modifying the Model
Customizing the Controller
Refining the View
Developing the User Management Functionality
Generating the Scaffold
Modifying the Model
Assigning Default Role to a User
Adding Display Action Method to the Controller
Refining the View
Adding the Assign Method to the Controller
Testing the Functionalities
Summary
5. Gathering User Comments
Understanding the Requirements
Login Management
Managing the Comments
Designing the Database
Designing the E-R Model
Deriving the Schema
Creating the Tables
Developing the Login Management Module
Creating the Login Page
Implementing the Authenticate method
Model
Controller
Setting up the Session
Applying Authorization
Tying Up the Loose Ends
Developing the Comment Management Module
Generating the Scaffold
Modifying the Model
Refining the View
Customizing the Controller
Testing the Module
Summary
6. Setting up the Template
Understanding Migration
Generating Migration Classes
Editing the Generated Classes
Running the Migration
Customizing the Template
Defining the Layout
Customizing the Layout of the Login Page
Defining the Master Layout
Defining and Applying the Master Layout
Setting up the Navigation
Testing the Application
Summary
7. Tagging the Tales
Understanding the Requirements
Developing the Tag management Module
Selecting a Plug-in for Tag Management
Installing the Plug-in
Setting up Tables Required by the Plug-in
Developing the Tag Management Module
Adding a Tag
Visualizing the Tag Cloud
Searching By Tag
Testing the Modifications
Summary
8. Enhancing User Experience with Ajax
Understanding the Requirements
Implementing Ajax
What is Ajax?
How Ajax and RoR are Related
Implementing the Live Search
Specify the Location to Display the Result
Use the observe_field Helper
Modify the Action Method
Implementing the In-line Editing
Marking the Fields for In-line Editing
Set up the Controller
Testing the Modifications
Summary
9. Developing the Interface for Administration
Understanding the Requirements
Implementing the Functionalities
Modification of the Deletion of Tales
Providing Access to All the Functionalities of the Comment Management Module
Implementing Auto-Complete for the User name
Implementing Search
Testing the Modifications
Summary
10. Deploying the TaleWiki
Understanding the Production Environment
Development Mode
Test Mode
Production Mode
Changing to the Production Environment
Migrating to the Production Database
Configuring Mongrel
Points to Consider
Summary
Index

Building Dynamic Web 2.0 Websites with Ruby on Rails

A P Rajshekhar

Building Dynamic Web 2.0 Websites with Ruby on Rails

Copyright © 2008 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, Packt Publishing, nor its dealers or distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

First published: March 2008

Production Reference: 1200308

Published by Packt Publishing Ltd.

32 Lincoln Road

Olton

Birmingham, B27 6PA, UK.

ISBN 978-1-847193-41-4

www.packtpub.com

Cover Image by Vinayak Chittar (<[email protected]>)

Credits

Author

A.P. Rajshekhar

Reviewer

Walt Stoneburner

Senior Acquisition Editor

Douglas Paterson

Development Editor

Ved Prakash Jha

Technical Editor

Mithun Sehgal

Editorial Team Leader

Mithil Kulkarni

Project Manager

Abhijeet Deobhakta

Project Coordinator

Zenab Kapasi

Indexers

Hemangini Bari

Monica Ajmera

Proofreader

Angie Butcher

Production Coordinator

Shantanu Zagade

Cover Work

Shantanu Zagade

About the Author

A.P. Rajshekhar, Senior Developer with Vectorform, has worked on enterprise-level web applications and game development. His endeavors include the development of a Learning Management System, Supply Management Solution, and Xbox-based games. He holds a Masters Degree in Computer Applications. He is a regular contributor to the Devshed Portal on topics ranging from server-side development (JEE/.Net/RoR) to mobile (Symbian-based development) and game development (SDL and OpenGL) with a total readership of more than 1.4 million.

Authoring a book is not an easy feat. However, the help and guidance from my family and friends helped me to author this book. First, I would like to thank Packt Publication for providing me an opportunity to work on such an exciting project. I would like to thank my parents for their constant encouragement. Special thanks to my friends Shrikant Khare and Sormita Chakraborty for their support and encouragement.

About the Reviewer

Walt Stoneburner is a software architect with over 20 years of commercial application development and consulting experience. Fringe passions involve quality assurance, configuration management, and security. If cornered, he may actually admit to liking statistics and authoring documentation as well.

He's easily amused by programming language design, collaborative applications, and ASCII art. Self-described as a closet geek, Walt also evaluates software products and consumer electronics, draws cartoons, produces photography, writes humor pieces, performs slight of hand, enjoys game design, and can occasionally be found on ham radio.

Walt may be reached directly via email at <[email protected]>. He publishes a tech and humor blog called the Walt-O-Matic at http://www.wwco.com/~wls/blog/. Rumors suggest that some of his strange videography may be found on iTunes.

Currently he is employed at Business & Engineering Systems Corporation as a lead engineer developing advanced software solutions for knowledge management.

Other book reviews and contributions include AntiPatterns and Patterns in Software Configuration Management (ISBN 0-471-32929-0, p. xi) and Exploiting Software: How to Break Code (ISBN 0-201-78695-8, p. xxxiii).

Preface

Ruby on Rails is an open-source web application framework ideally suited to building business applications, accelerating and simplifying the creation of database-driven websites. It has been developed on the Ruby platform.

This book is a tutorial for creating a complete website with Ruby on Rails (RoR). It will teach you to develop database-backed web applications according to the Model-View-Controller pattern. It will take you on a joy ride right from installation to a complete dynamic website. All the applications discussed in this book will help you add exciting features to your website. This book will show you how to assemble RoR's features and leverage its power to design, develop, and deploy a fully featured website.

What This Book Covers

Chapter 1 gives you an overview of the features of Ruby and RoR, as well as providing the various ways of installing, configuring, and testing both Ruby and RoR.

Chapter 2 introduces you to the basics of Ruby as well as the main concepts and components of RoR.

Chapter 3 makes you understand the design of tables according to the conventions of RoR, creation of scaffolds for tables, and changing the scaffolds according to the requirements.

Chapter 4 gives you details about how to set up the User Management module for the website called TaleWiki.

Chapter 5 makes you familiar with the Login Management and Comment Management modules for TaleWiki.

Chapter 6 introduces you to the Migrations and Layouts involved in setting up the template for TaleWiki.

Chapter 7 describes the tagging functionality being implemented for the enhanced search usability.

Chapter 8 provides you with the implementation of AJAX for TaleWiki.

Chapter 9 deals with the development of an interface for the administration.

Chapter 10 gives you the steps for deploying the website.

What You Need for This Book

Operating System: Windows 2000 or above / Redhat Fedora core 1.0 or aboveDatabase: MySQL 4.9 or aboveEditor: Notepad/Vim or EmacsBrowser: Firefox 1.5 or above/ Internet Explorer 6.0 or above

Conventions

In this book, you will find a number of styles of text that distinguish between different kinds of information. Here are some examples of these styles, and an explanation of their meaning.

There are three styles for code. Code words in text are shown as follows: "For example, to add instance attributes named author and genre to the Tale class, you will do it as follows:"

A block of code will be set as follows:

class Tale @author @genre @tale_body end

When we wish to draw your attention to a particular part of a code block, the relevant lines or items will be made bold:

class Tale @author @genre @tale_body end

Any command-line input and output is written as follows:

c:\InstantRails\rails_apps\ > rails talewiki

New terms and important words are introduced in a bold-type font. Words that you see on the screen, in menus or dialog boxes for example, appear in our text like this: "In the next page, without entering any data, click on the Create button."

Note

Important notes appear in a box like this.

Tip

Tips and tricks appear like this.

Reader Feedback

Feedback from our readers is always welcome. Let us know what you think about this book, what you liked or may have disliked. Reader feedback is important for us to develop titles that you really get the most out of.

To send us general feedback, simply drop an email to <[email protected]>, making sure to mention the book title in the subject of your message.

If there is a book that you need and would like to see us publish, please send us a note in the SUGGEST A TITLE form on www.packtpub.com or email <[email protected]>.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide on www.packtpub.com/authors.

Customer Support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the Example Code for the Book

Visit http://www.packtpub.com/files/code/3414_Code.zip to directly download the example code.

The downloadable files contain instructions on how to use them.

Errata

Although we have taken every care to ensure the accuracy of our contents, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in text or code—we would be grateful if you would report this to us. By doing this you can save other readers from frustration, and help to improve subsequent versions of this book. If you find any errata, report them by visiting http://www.packtpub.com/support, selecting your book, clicking on the Submit Errata link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata added to the list of existing errata. The existing errata can be viewed by selecting your title from http://www.packtpub.com/support.

Questions

You can contact us at <[email protected]> if you are having a problem with some aspect of the book, and we will do our best to address it.

Chapter 1. Getting Started with Ruby and RoR

'Which is the best framework for web application development?' This question is asked in different ways and forms. The answer, however, always remains the same—'The one that enhances productivity'. The next obvious query would be 'In that case which is the framework that enhances productivity?' After some debates and deliberations, we can conclude, 'A framework that reduces Boilerplate code and also reduces the learning curve is the one that increases productivity.'

If you look around, there are an abundance of frameworks that cater to web application development. But most of them fail in one of the two points that govern productivity. Either the framework reduces the Boilerplate code or it is easier to learn. Achieving a balance between the two is seen as a tough task. It is here that Ruby and Ruby on Rails (or RoR as it is fondly called), score above most of their contemporaries. How they achieve this balance is what we will be looking at in this book.

We will be developing a website throughout the book, each chapter adding something new to the website. This chapter will lay the groundwork of introducing you to Ruby and RoR. It will also tell you the ways to install and configure Ruby and RoR—one-click as well as manual installation, and finishing with techniques to test your installation.

Ruby and RoR—The Next Level in Dynamic Web Development

It is always a good idea to know about the specifications of the tool with which one has to work, before handling the tool. In our context, the tools are Ruby and RoR—Ruby as the language and RoR as the framework built upon Ruby.

Ruby

In 1995, Yukihiro Matsumoto released the first version of Ruby and this added one more language to the ever-growing toolkit of application developers. The current stable version is 1.8.6. According to the TIOBE Programming Community Index, it is the fastest growing language. So, what makes it the fastest growing one among the languages? To understand this, let us first understand the reason behind the creation of Ruby. The main reason given by Mr. Matsumoto for creating Ruby was that he wanted a scripting language that would optimize the way a programmer would develop the software. This means that the features of Ruby are such that they optimize the way the software is developed. What are these features? Let us have a look at them:

Interpreted: Ruby is an interpreted language. Therefore, whenever you make a change to the source code, you need not compile the code and then run it to see the effect of the change. As a result of this feature, the code-compile-run cycle becomes the code-run cycle.Purely Object-Oriented: Ruby is purely object-oriented. That means that everything in Ruby is an object which includes primitive data-types and numbers. In addition, it supports all the features required by an Object-Oriented Language.Functional: Ruby supports functional programming using blocks.Duck Typing: It is also known as Dynamic Typing. Ruby decides about the type of variable while the program is running by looking at the value contained in the variable at that instant. In other words, if an object looks like a duck, sounds like a duck, then it is a duck!Automatic Memory Management: You would know it as Garbage Collection. As in any Very High-Level Language (VHLL), Ruby provides Garbage Collection out-of-the-box, thus you need not worry about physical memory leaks.Threading: The current stable version of Ruby provides 'almost' platform independent threading using green threads (threads used at the user-space level are known as green threads.) I said 'almost' because Ruby threads are simulated in the VM rather than running as native OS threads.Reflection: Ruby provides a program with the ability to 'look at itself' while running. This ability is known by different terms, such as reflection, introspection, and so on. Using reflection, a program can modify certain aspects of itself during execution, or create a completely new object at runtime based on the requirements at that time.

Looking at the features we just discussed, you could definitely see that the creator's reason holds true. The way imperative programming features have been balanced with functional programming is the proof of that. It is on such a foundation that RoR has been built.

Ruby on Rails (RoR)

RoR is a recent entrant in the world of web application frameworks. So how come such a new player on the block not only stands on its own but can also challenge veteran players of the likes of J2EE/JEE? The answer does not just lie in the functionalities. The other aspect that governs the acceptance of a framework is its philosophy. Hence, we will have to look at both the aspects of RoR—functionality as well as philosophy. Keep in mind that the philosophy holds true for all the versions of RoR.

Philosophy

The philosophy of RoR depends on two principles:

DRY: Don't Repeat Yourself or the DRY principle, if applied properly, reduces the duplication of tasks within a project. Duplication of any kind, within a project, leads to difficulty in modification and maintenance and inconsistency. In RoR, you can see this principle at work in almost everything—from the reusable components in the form of plug-ins to the way database tables are mapped.Convention-over-Configuration(CoC): Configuration has taken over the web application frameworks so much that even a simple task such as applying 'compulsory field' validation for just one field requires entries in an XML file. In RoR, the principle is to supply information about only those aspects that are different from usual application settings. The ORM (Object Relational Mapping) framework provided by RoR is an example of the Convention-over-Configuration principle. Unless you specify a different name for an ORM object, the object uses the name of the table to which it is mapped. Whereas in the case of configuration-based ORM frameworks, such as Hibernate, the mapping of each table along with its columns has to be given in the configuration file. So, a change in the schema means a change in the configuration file. However, in the case of RoR, a change in the schema doesn't mean a change in the object unless the name of the table itself changes. We will see more about the ORM framework in Chapter 2.

Features

The features based on the philosophy of DRY and Convention-over-Configuration principles are what make RoR so attractive for the development of dynamic web-sites. The features that showed the way for alternative methods for implementation of various server-side techniques are:

Automatic setup of Application structure: If you have worked with J2EE technologies, this would come as a pleasant surprise. The structure of any application need not be created manually. Just one command and the complete structure including folders and basic web files such as index.html will be generated for you. Therefore, no more hunting for third party tools such as those that provide the initial setup or setting up the structure manually.Generation of Boilerplate Code: Every application has certain blocks of code that are essentially the same for all other applications of the same type or category. Such blocks are called Boilerplate code. One of the examples of Boilerplate code is the code block setting up a connection to the database. The same code can be used with different applications with only a little change. Though this is the case, most of the frameworks do not provide any inbuilt mechanism to reduce this 're-invention of the wheel'. RoR avoids the duplication using scaffolding. In essence, a scaffold contains the bare minimum of code to accomplish tasks such as connecting to the database, setting up a log, and so on. Scaffolds reflect the DRY principle that RoR adheres to.Dynamic mapping of classes to database schemas: No web application can go online without having a database as its back-end. ORM frameworks have eased the database access. However, the configuration aspect reduces any advantage to the developer. In the case of RoR, ORM does not need any configuration. At runtime, RoR reads and maps the schema based on the names of classes and corresponding tables using reflection and meta-programming. Moreover, what the developer gets is more productivity.Ajax at the core of presentation: Ajax is the technology that provides interactivity to websites without becoming intrusive. All the current server-side technologies claim to support Ajax, but the support is peripheral and not at the core. You would have to download new libraries, configure them, and then start the develop-compile-deploy-test cycle again. Whereas in RoR, Ajax is part of the core libraries. So when you install RoR, Ajax support is also made available to you. Using them is as easy as when you use any other library provided by RoR.Batteries included: RoR contains many more libraries that provide for essentially all the requirements of a dynamic website including layout management, mailing, and so on. If you look at these libraries, you will understand that they are, in fact, fully-fledged components in themselves, representing different services provided by a website or a portal.

That completes the roundup of features of the 'tools' that we are going to use to build our website. The next step is to install and configure our 'tools' so that we can get started with our task.

Installing and Configuring Ruby and RoR

RoR can be installed in two ways:

Manual installation after installing Ruby One-click installer that installs Ruby and RoR, which includes Apache web-server and MySQL database server

If you already have Apache and MySQL installed, then manual installation is the better way as it installs only RoR.

Manual Installation

There are three main steps for manually installing RoR, which are:

Downloading and installing RubyUpdating gemInstalling RoR using gem

In this case, the RoR installation is done over the internet. So from the second step itself, ensure that the internet is connected throughout the installation.

Downloading and Installing Ruby

First, grab the Ruby installer for windows at http://rubyinstaller.rubyforge.org/wiki/wiki.pl.

The previous figure shows the main page for the one-click Ruby installer (do not confuse it with one-click RoR installer). It provides a list of links that provide details about the one-click installer. Here are the steps for downloading and installing Ruby:

From the list, select [Download] link.On clicking the [Download] link, you will be taken to the page listing the downloadable release version of the installers.From the given list, select the .exe link for the latest release and save the file in your preferred location. In our case the version to be downloaded is ruby186-25.exe.Double click on the file to be installed to start the installation process.The first screen that will be presented to you should be the License Agreement. Read the license carefully and click on I Agree.

The next screen will present you with the components to be installed.

Keep the default choices and click Next. Of these SciTE is a programmer's editor and RubyGems is Ruby's package manager and updater.Next, choose where Ruby should be installed. It's always advisable to install in the root of any drive instead of a sub-folder. Ruby commands may not work correctly if the sub-folder is deeply nested. For example, if you want to install it in drive C:, then give c:\ruby as the value for Destination Folder. Also keep in mind not to specify any folder name with spaces in it, as it may create problems while installing RoR.Next, provide the name for the Start Menu entry for Ruby installation. Keep the default name and click Install.

If the installation completes without any problem, then you will see the following screen:

Click on the Next > button to complete the installation process.The last screen presented by the installer should give you an option to view the Readme file. If you wish to read it, check the Show Readme checkbox and then click on Finish to complete the installation.

That completes the Ruby installation. The next step is to update the installation using gem.

Updating Gem

Gem is the name of the utility supplied with Ruby in order to manage, install, and update the Ruby installation in an easy way. The second step in the manual installation of RoR is updating the Ruby installation so that if a new package or an update for any of the package is available, then the complete installation can be made up-to-date.

Before we begin, if you are behind a proxy, open the command prompt and give the following command:

>Set HTTP_PROXY=http://<proxy_address>:<proxy_port>

For example, if the address of the proxy server is 192.168.1.1 and the port number is 9090, then you would have to give the following at the command prompt:

>set HTTP_PROXY=http://192.168.1.1:9090

Next, give the following command at the prompt:

>gem update

You will get the following reply after the last step:

Select the compatible version for your platform. Here I choose option 2 which is the latest for Windows. The difference between <ruby> and <mswin32> is that the former is a pure Ruby-based package and the latter is the packages natively compiled for Windows. If there is more than one package to be updated, then more 'choice menus' will be presented to you. The point to remember is to choose the number corresponding to the latest version of the package natively compiled for Windows.

That completes the update gem step. Next, let us install RoR.

Installing RoR

This is the last and the easiest part of the installation process. Just one command and RoR shall be installed. At the prompt, issue the following command:

>gem install rails --include-dependencies

The command should give the messages as shown in the previous figure. Congrats! RoR is now installed on your system.

Note

For those working on GNU/Linux, only the first step would differ. To install Ruby, grab the latest tar file from http://www.ruby-lang.org/en/. Then give the following command at the prompt:

tar zxvf <ruby_tar_file>

Then go into the directory created by the tar command. Inside the directory issue following commands:

./configure; make; make install

That's it. Ruby is ready to be explored.

One-Click RoR Installation

The one-click installer is, in fact, a zip package containing everything that you need. All you need to do is download it and unzip it to a directory of your choice. Even though, it is in a single package, the installation needs to be configured. Therefore, in essence, there are two steps:

Download and Unzip the Instant Rails

First, go to the following address:

http://instantrails.rubyforge.org/wiki/wiki.pl.

From the links listed on the page click on the [Download] link.On the next page, select the package corresponding to the latest release from the list.