Back to description
Ruby on Rails is opinionated software. This doesn’t mean that it’s going to make fun of your haircut, or tell you what kind... more
Ruby on Rails is opinionated software. This doesn’t mean that it’s going to make fun of your haircut, or tell you what kind of car to drive. It does mean that Rails has definite ideas about how your web project should be structured, how it should interact with a database, how you should test, and even what kinds of tools you should use. Tasks which Rails feels that you should do often are easy, and tasks which Rails thinks should be rare are (usually) possible but more complicated. This works because the Rails team has done an exceptionally good job of deciding how web projects should work, and how they should not work.
Two important principles that Rails favors are especially useful when starting a new Rails project:
Representational State Transfer (REST) is a relatively new mechanism for structuring a Rails application by organizing the application around resources, rather than pages.
Test Driven Development (TDD) is an important part of ensuring the correctness and design of any software project, but Rails does a particularly good job of providing the developer with the tools needed for easy and powerful automated testing.
In this chapter, you will begin the construction of the Rails project that will carry you throughout the book. This will enable you to review the basic Rails functionality you should already be familiar with, but with an added emphasis on REST and TDD. At the end of this chapter, your Rails knowledge should be refreshed, state-of-the-art, and ready to go.
Note
To run the examples throughout this book, a standard suite of applications is assumed to already be installed on your computer. The suite includes Ruby, Rails, MySQL, and Subversion. See Appendix A, “Things You Should Download,” for details on how to install these tools.
... less
Every software project needs to manage its source code. Developers on the project need to be able to find code within the... more
Every software project needs to manage its source code. Developers on the project need to be able to find code within the project. Multiple people need to be able to work together on the project and see each other’s work without accidentally overwriting it. And you need to make sure that nothing is ever, ever lost.
Rails provides a standard project layout, which helps with the first issue. For the second and third issues, you need to turn to a source control system. That system will allow each developer to retrieve code from a common repository and then return their changes to the repository. As soon as a developer has placed their changes back in the repository, other developers on the project can update their local copies of the code to see the changes. If two developers are working on the same file at the same time, the source control system manages the combination of the two pieces of work so that neither is lost. Using a source control system, you can recreate any past state of your application at any time.
Core Rails development (and most Rails plugin development) is performed using a version control system called Subversion, which has become the standard tool for many open-source projects. Because so much existing Rails development uses Subversion, you can get some benefits from using it in your own development. In this chapter, you’ll learn how to set up your Rails project using Subversion, and how to use it to stay on the cutting edge of Rails development.
You can’t have a community website without users. Users set the tone for your site, commenting in forums, adding information... more
You can’t have a community website without users. Users set the tone for your site, commenting in forums, adding information, noticing mistakes, giving reviews, rating, and tagging. At the same time, allowing user accounts opens your site to spam, data risks, session capturing risks, and so on. Proper management of your user data can make your site resistant to common user permission and security issues.
In this chapter, you add users to Soups OnLine. First, you create user accounts see how to prevent automated accounts from gunking up your database. Then, you add user authentication and session management to your Rails controllers. And finally, you examine user roles and how to implement them.
Automation is critically important to the success of an ongoing project. As the project continues, you will accumulate task... more
Automation is critically important to the success of an ongoing project. As the project continues, you will accumulate task after taskthings that need to be done over and over again to keep the project running smoothly. These include cleanup tasks to remove unneeded files or database entries. Depending on the project, you may have to build tasks for compiling or interpreting files in advance. You’ll have deployment tasks, to move your program from the development environments to your production servers.
These tasks need to be done repeatedly and they need to be done accurately, which makes them prime targets for automation. And so, for decades, programmers have defined repetitive tasks in various kinds of make files, named, of course, after the original Unix make programthe granddaddy of all programs used to define build tasks.
make
The key element of make-like system is the capability to define tasks as being dependent on other tasks. For example, a testing task might depend on a database setup task running first. Or a deployment task might depend on a clean rebuild of the entire project being completing successfully before deployment can begin. The complexity of a make system comes not just from defining the tasks themselves, but also from defining the dependency trees between tasks.
The classic make application is often considered to have a difficult-to-read syntax, and is still most widely used within Unix and C development worlds. Other programming communities have developed other tools. Many Java projects use Ant, which has an XML-based syntax for defining tasks and dependencies. However, Ant files also have a tendency to become unwieldy as they get more complex over time. (As software guru Martin Fowler said, “Until we tried it, I thought XML would be a good syntax for build files.”)
Most Ruby projects now use Rake (Ruby Make), which uses Ruby’s flexible syntax to combine a readable dependency syntax with the full power of Ruby in defining tasks. When you use Rake in your Rails project, you also have full use of your ActiveRecord models, which is nice. Ruby comes with a large number of predefined tasks (some of which you’ve seen already) that perform a number of useful Rails tasks. You can, of course, write your own tasks specific to your own project.
When you can run your build tasks automatically, you can run them all the time. This is especially useful for compilation and test tasks. Continuous integration has proven to be so useful, that a number of tools have been developed specifically to enable your Rake-based project to run its tests automatically on a regular basis.
Another tool called Capistrano has emerged to support the complex job of deploying a Rails application to multiple production servers. Capistrano extends Rake to support transferring files and ensuring consistency among deployment servers.
When you last looked at the Soups OnLine application, you had just added user logins. However, you haven’t actually given... more
When you last looked at the Soups OnLine application, you had just added user logins. However, you haven’t actually given the users very much to do besides create an account and add and edit their own recipes. Right now, the users have no way to browse the site or find recipes based on ingredients or keywords. It also would be nice if users could provide feedback on recipes and see the feedback that other users have left.
One of the best features of Rails is that it protects you from many of the most irritating details of working with relational... more
One of the best features of Rails is that it protects you from many of the most irritating details of working with relational databases. For most purposes, you don’t need to remember the command line syntax, unusual GUI viewer, departures from the SQL standard, or other maintenance quirks because you sit comfortably behind the shield of Rails protective abstractions.
Databases, however, are subtle and powerful, and you cannot escape their awesome might for long. There are a few situations in which a Rails developer might have to display an unusual knowledge of the details of the underlying database. One of those situations is when you are forced to use a preexisting legacy database.
Opinionated framework that it is, Rails has certain expectations about the naming and structure of database tables. It assumes, for example, that each table has a single primary key and that the name of that primary key is id. Similarly, Rails assumes that a foreign key for a relationship has a predictable name based on the table being linked to. Those conventions enable a Rails developer to consistently understand the structure of the model objects based on the database schema and vice versa.
id
All of which works great if you are in a position to create and maintain your own database schema. But that is often not the case. Sometimes you’re brought into a project and the data already exists, and other existing projects depend on the schema, so you can’t change it to bring it in line with Rails standards.
If you are in a situation where you have an existing database schema to work with, you need to decide how to manage it. Depending on the exact nature of your project, you might be able to try one or more different options. You’ll need to decide whether to split your application into two databasesone that is created by Rails and uses Rails conventions, and the other for the existing legacy systemor leave the entire system in the legacy schema and extend it as needed. Migrating all the data from the existing schema to a Rails database might also be an option.
All these solutions have pros and cons. Migrating all data to a Rails database is the smoothest for Rails development, but requires the development and maintenance of a separate migration application. Also, if the migration is applied frequently and affects a lot of data, this could have implications for caching and other tasks that require stable object relationships. Leaving the legacy database alone is probably best where the legacy database has a consistent naming convention of a kind that Rails can be readily adapted to follow. If not, then every table is going to need special-case treatment, which can be error prone. Splitting the database is a good choice if the legacy database is legitimately a subset of the entire application (such as a preexisting user mailing list database), or if you have hopes of seeing the Rails code assimilate the existing data, Borg-like, one table at a time. On the down side, much of ActiveRecord is written assuming a single source of datathe second source of data is excluded from many of ActiveRecord’s best tricks. Personally, unless the existing database has a very good naming convention, I tend to favor creating a second database with Rails defaults for models that may arise during a project’s lifecycle. I think it’s less painful to deal with two database systems then to have no Rails convention in the project at all. Your mileage may, of course, vary.
Don’t panic. Rails has tools that will allow it to manage the data in the legacy system with almost the same ease that you’ve come to expect. There are four issues to manage: connecting to the database in the first place, managing whatever weird naming conventions Fred in IT came up with, allowing for ActiveRecord relationships, and managing testing against the new schema.
In this book, I’ve put testing front and center for the simple reason that I believe that automated testing is a critically... more
In this book, I’ve put testing front and center for the simple reason that I believe that automated testing is a critically important method for ensuring both code quality and long-term code maintainability. So far, I’ve focused on Ruby’s standard Test::Unit structure as the primary tool in the testing toolkit. And while Test::Unit is a very important part of automated testing, it’s far from the only tool you should be using to ensure that your Rails application is fully and completely tested.
In this chapter, you’ll fill out your toolkit a bit and examine why each new tool is vital to your being a test-driven developer. You’ll see how to measure the amount of code that is touched by your tests, and how you can use mock objects to improve your code and reach otherwise-difficult-to-cover parts of the code. Then you’ll look at some tools for behavior-driven testing, a technique that uses mock objects extensively. Finally, you’ll see a way to separate controller and view tests in Rails.
As it happens, I spent a significant part of the years 1999 and 2000 arguing against putting large amounts of JavaScript... more
As it happens, I spent a significant part of the years 1999 and 2000 arguing against putting large amounts of JavaScript in the client sites I was developing. My arguments were that the tool support was weak, so a lot of developer effort was involved, it was hard to debug, and almost anything complex was guaranteed to break on one or the other of the two major browsers. Furthermore, the range of things people were doing with JavaScript at the time wasn’t so compelling that it seemed to require throwing it into our sites.
That was a long time agothe iPod didn’t even exist yetand times have changed. JavaScript is now a critical part of many of the Web’s most popular sites. Much of this has been driven by a simple functionality enhancement that did not exist in 2000: the capability to call a server asynchronously from within JavaScript. That simple capability, from the XmlHttpRequest object that is now a standard part of JavaScript, has enabled a much richer and more interactive Web experience, ranging from special effects, to Ta-Da Lists, to scrolling Google Maps, to rich online document editing. Eventually, the new interaction structure was isolated and named Ajax, which is a pseudo-acronym for Asynchronous JavaScript And XML, and the name has stuck.
XmlHttpRequest
Rails was one of the first toolkits to make dealing with Ajax easy to do without having to know a great deal of JavaScript. Since the initial release of Rails, the addition of RJS scripts has made it even easier to add dynamic content to a Rails application without touching JavaScript very much. In this chapter, I focus on the features within Rails that deal with JavaScript. JavaScript is a very interesting object-oriented language in its own right, and the Prototype and script.aculo.us libraries that Rails uses have a lot of functionality to support cool Ajax effects. In this chapter, I’ll be discussing them through the lens of their Rails interactions.
Increasingly, the content produced by web applications and distributed over web servers is aimed not directly at the user... more
Increasingly, the content produced by web applications and distributed over web servers is aimed not directly at the user, but at other computer programs that use the data in different ways. Applications can take web data and present it to the user in a different user interface (UI)such as the Twitteriffic application, which gives Twitter a Mac OS X front-end. Or a site can aggregate data from multiple sitessuch as Bloglines or Google Reader.
All it really means to be a web service is to output data from HTTP requests in a machine-readable format. At the moment, XML is the most common format (especially because the RSS format for blog syndication is just a specification within XML). In fact, the formal definition of web services seems to sort of absurdly say that a web service can only be in XML. However, you’ll frequently see JavaScript Object Notation (JSON) used (especially for data specifically earmarked for Ajax and JavaScript), and most web pages still render HTML, so it’s useful to have a tool that can extract useful data from those pages as well.
There have been a few attempts to standardize web services. These days, the most prominent standards are SOAP (which is currently an ex-acronym because the original acronym was officially declared misleading) and REST (REpresentational State Transfer), which has already cropped up numerous times in this book. Without getting into the detailed arguments over which standard is better, the Rails core team has chosen REST as a preferred mechanism for managing web services from Rails. As a result, this chapter focuses on REST and similar lightweight web communication systems such as RSS and Atom. It also tackles producing web service data and consuming web services.
A funny thing happens when you put your application on the World Wide Web. People start accessing it from all around the... more
A funny thing happens when you put your application on the World Wide Web. People start accessing it from all around the world. Even my tiny little blog (10printhello.blogspot.com), which gets a whopping 20 hits per day as I write this, has gotten visitors from 60 different countries or territories during the past month.
10printhello.blogspot.com
This is a wonderful thing, and I wouldn’t change it. But it can make things complicated for you as the developer of a web application. For one thing, all of these visitors insist on living in different time zones. Most of them don’t speak English, and respond to different cultural cues based on color or icon elements. They use other currencies, and are subject to different laws, the details of which might be critically important depending on what kind of site you are operating.
This chapter discusses various facets of internationalization and localization, starting with how to manage dates and times, and moving on to how to support running your site in multiple languages and locales.
The biggest innovation in the original NCSA Mosaic web browserthe one that that changed the Web from just a way to hyperlink... more
The biggest innovation in the original NCSA Mosaic web browserthe one that that changed the Web from just a way to hyperlink physics papers into a multimedia content platformwas the img tag, supporting inline image display. Since then, the capability to manipulate graphics has remained an important part of working on the Web.
img
This chapter examines several ways to integrate dynamic graphics into your web system. You’ll see how to acquire images from the user via file upload. You’ll explore the various libraries available for manipulating images from within Ruby, and take a look at some packages for creating charts from those images.
It’s inevitable. At some point your Rails application has to leave the comforting home of your development setting and make... more
It’s inevitable. At some point your Rails application has to leave the comforting home of your development setting and make its own way in the cold, cruel world of production environments. Deploying Rails applications has been an area of extremely rapid change and developmenteven by Rails standardswith the definition of deployment best-practice tools changing completely every few months. As I write this, though, the field appears to have settled on a consistent set of tools. This toolset is designed to take you from your development environment to low-traffic, high-traffic, and very-high–traffic production sites using the same basic technologies.
Every deployment is different, of course, and the requirements for deploying high-traffic Rails sites like Basecamp or Twitter are different than you might need for an internal sales tool, or for a soup-recipe trading site. This chapter focuses on two of the most generally valuable tools in the Rails deployment kit: Capistrano, which is used to automate deployment activities, and Mongrel, which has emerged as the Rails application server of choice.
Deployment can be complex, and one of the best ways to mitigate that complexity is to start practicing the deployment early and often. Even during the earliest part of development, you should try to set up a staging server and start deploying to it, to test out all the various connections between the web server, source control, the database, and so on. That also gives you a platform to try out various server configurations and do some baseline performance measurements. This chapter gives you the basic tools to manage your deployment. The next chapter tackles managing performance and security on a production Rails application.
If you are lucky, when your web application goes out into the world, it will be used. Users are lovely people in general,... more
If you are lucky, when your web application goes out into the world, it will be used. Users are lovely people in general, but they tend to have some specific expectations about the responsiveness of a web applicationexpectations that have been honed from years of using Google. Of course, Google has spent millions of dollars on server farms the size of football fields while you have two Linux boxes on a rack in a back room somewhere.
This chapter tackles strategies for keeping your web application’s performance up to speed. You’ll look at some mechanisms for identifying under-performing code, and then examine common bottlenecks and performance issues in Rails applications.
If you’ve been playing along with the book to this point, you’ve created a functional (albeit quirky) Ruby on Rails application... more
If you’ve been playing along with the book to this point, you’ve created a functional (albeit quirky) Ruby on Rails application, added some features, and deployed it. What’s left? In the real world, you’d move the deployed code to a separate Subversion branch for bug fixes, and move on to version 2.0. In our book world, the next few chapters will be spent talking about various extensions and expansions of Ruby and Rails that are going to be useful additions to your set of tools.
First up is Ruby and metaprogramming. Ever since Rails first came out, it has been accompanied by claims that the Ruby programming language is not just a useful way to script behavior, but an integral part of the Rails architecture. There were also remarks that Rails could only have been written in Ruby, although now that most of the major features have been ported (one way or another) to other languages, you hear that somewhat less these days. Even so, all the statements about how Rails depends on Ruby are responding to something real and different about Ruby: its extraordinary support for changing the program’s context and structure at runtime, or metaprogramming.
Throughout the book, you’ve seen some examples of how metaprogramming can be used to create elegant and flexible code, and you’ve also seen a little bit of how metaprogramming constructs are used throughout Rails. In this chapter, you’ll take a full tour of Rails metaprogramming and see how it can be used effectively.
Any discussion of metaprogramming tends to bog down because the concepts are kind of mind-twisting and everybody tends to use a slightly different set of terms. For our purposes here, metaprogramming is any attempt to dynamically change not just the data that the program is running on, but the actual code structure itself. The structural change can be as simple as using an eval statement to dynamically generate code to execute or as complex as a Rails plugin changing the behavior of preexisting core Rails tasks.
eval
Ruby on Rails has become a complex framework, and it has a lot of useful features. But it doesn’t have every feature every... more
Ruby on Rails has become a complex framework, and it has a lot of useful features. But it doesn’t have every feature every user wants. The Rails design team has deliberately chosen not to try and put every imaginable feature in core Rails, a decision backed in Rails 2.0 by the removal of several features out of the core (admittedly, there are still a lot of features there). The Rails mechanism for managing feature overload is the plugin system, which does a fantastic job of delivering Rails extensions of all kinds to the user community. The Rails community as a whole has augmented Rails in every imaginable direction, in a vibrant and active ecology. If you’re doing something in your website, and it’s a feature that applies to other websites, odds are there’s a plugin to help you with it. If there’s not, bundle one up and distribute it yourself.
This chapter discusses a few ways to extend Rails, starting with plugins. Although several plugins have already been used in the development of Soups OnLine, there are still some features of plugin management that are worth talking about. You’ll also see how to create your own plugins and generators.
Ruby and Rails are linked together tightly, but not so tightly that they can’t be pried apart here and there where it makes... more
Ruby and Rails are linked together tightly, but not so tightly that they can’t be pried apart here and there where it makes sense to do so. In this chapter, you’ll explore various ways to use Rails and languages or tools other than Ruby itself.
A Ruby on Rails application is made up of many parts. Although the installation of the gems and plugins used in a Rails application... more
A Ruby on Rails application is made up of many parts. Although the installation of the gems and plugins used in a Rails application is covered in the main text, the installation of the basic pieces is not covered consistently. This appendix provides a brief guide to what to download and where to get it.
Rails has had a bit of an influence on the larger world of web frameworks. This appendix introduces you to a series of other... more
Rails has had a bit of an influence on the larger world of web frameworks. This appendix introduces you to a series of other frameworks that were inspired by Rails in one way or another. Some are attempts to bring the Rails design philosophy to other languages; others are Ruby-based attempts to create an even more lightweight framework.
Purchase Before purchasing this product, please be sure you have met all software and system requirements, and that you understand any limits placed upon its use.
Return Policy Wrox Chapters on Demand are non-returnable and non-refundable.
Watermarking Wrox Chapters on Demand are sold with a small unique watermark at the bottom of each page identifying the purchaser name, email address, and order number.
Reader Software Wrox Chapters on Demand are offered as PDFs, and they can be viewed using the Adobe Reader, ADE, or a compatible PDF reader. If you do not have the Reader installed, it can be downloaded for free at Adobe.com.
Test Download As Wrox Chapters on Demand purchases are non-returnable, it is advisable that you test your system and software configurations with a free sample download before you place an order.
Usage Rights for a Wrox Chapters on Demand File Any Wrox Chapters on Demand product you purchase from this site will come with certain restrictions that allow Wiley to protect the copyrights of its products. After you purchase and download this title, you:
If you have any questions about these restrictions or need any further assistance please refer to Technical Support (www.wiley.com/techsupport) or call (877) 762-2974 (8 a.m. - 5 p.m. EST, Monday - Friday).
Related Books