Learn Ruby on Rails: the Ultimate Beginner’s TutorialBy Patrick Lenz
Rather than having us create all of our application code from scratch, Rails gives us the facility to generate an application’s basic structure with considerable ease. In the same way that we created our application’s entire directory structure, we can create new models, controllers, and views using a single command.
To generate code in Rails, we use the generate script, which lives in the script folder. Give it a try now: type ruby generate without any command line parameters. Rails displays an overview of the available parameters for the command, and lists the generators from which we can choose, as Figure 4.6 illustrates.
Figure 4.6. Sample output from
Rails can generate code of varying complexity. At its simplest, creating a new controller causes a template file to be placed in the appropriate subdirectory of your application. The template itself consists of a mainly empty class definition, similar to the
Author classes that we looked at earlier in this chapter.
However, code generation can also be a very powerful tool for automating complex, repetitive tasks; for instance, you might generate a foundation for handling user authentication. We’ll launch straight into generating code in Chapter 5, Models, Views, and Controllers, when we begin generating our models and controllers.
Another example is the generation of a basic web-based interface to a model, referred to as scaffolding. We’ll also look at scaffolding in Chapter 5, Models, Views, and Controllers, as we make a start on building our views.
While not strictly part of the web, email is a big part of our online experience, and Rails’s integrated support for email is worth a mention. Web applications frequently make use of email for tasks like sending sign-up confirmations to new users and resetting a user’s password.
ActionMailer is the Rails component that makes it easy to incorporate the sending and receiving of email into your application.
ActionMailer is structured in a similar way to ActionPack in that it consists of controllers and actions with templates.
While the creation of emails, and the processing of incoming email, are complex tasks,
ActionMailer hides these complexities and handles the tasks for you. This means that creating an outgoing email is simply a matter of supplying the subject, body, and recipients of the email using templates and a little Ruby code. Likewise,
ActionMailer processes incoming email for you, providing you with a Ruby object that encapsulates the entire message in a way that’s easy to access.
Adding email functionality to a web application is beyond the scope of this book, but you can read more about
ActionMailer on the Ruby on Rails wiki.
Testing and Debugging
A number of different types of testing are supported by Rails, including automated and integration testing.
The concept of automated testing isn’t new to the world traditional software development, but it’s fairly uncommon in web application development. While most Java-based web applications make use of comprehensive testing facilities, a large number of PHP and Perl web applications go live after only some manual tests have been performed (and sometimes without any testing at all!). Although performing automated tests may be an option, developers may decide not to use them for reasons ranging from the complexity of the task to time constraints.
We touched on this briefly in Chapter 1, Introducing Ruby on Rails, but it’s worth stressing again: the fact that comprehensive automated testing is built into Rails, and is dead easy to implement, means there’s no longer a question about whether or not you should test your apps: just do it!
generate command that we introduced a moment ago can automatically create testing templates that you can use with your controllers, views, and models. (Note that Rails just assists you in doing your job, it’s not replacing you — yet!)
The extent to which you want to implement automated testing is up to you. It may suit your needs to wait until something breaks, then write a test that proves the problem exists. Once you’ve fixed the problem so that the test no longer fails, you’ll never get a bug report for that particular problem again.
If, on the other hand, you’d like to embrace automated testing completely, you can write tests to ensure that a specific HTML tag exists at a precise position within a page’s hierarchy. (The hierarchy referred to here is the Document Object Model (DOM), a W3C standard for describing the hierarchy of an (X)HTML page.) Yes, automated tests can be that precise.
Rails’s testing capabilities also include integration testing.
Integration testing refers to the testing of several web site components in succession — typically, the order of the components resembles the path that a user would follow when using the application. You could, for example, construct an integration test that reconstructs the actions of a user clicking on a link, registering for a user account, confirming the registration email you send, and visiting a page that’s restricted to registered users.
We’ll look at both automated testing and integration testing in more detail in later chapters.
When you’re fixing problems, the first step is to identify the source of the problem. Like many languages, Rails assists this process by providing the developer (that’s you!) with a full stack trace of the code. As we saw earlier, a stack trace is a list of all of the methods that were called up to the point at which an exception was raised. The list includes not only the name of each method, but also the classes to which those methods belong, and the names of the files in which they reside.
Using the information contained in the stack trace, you can go back to your code to determine the problem. There are a few different ways to approach this, depending on the nature of the problem itself:
- If you have a rough idea of what the problem might be, and are able to isolate it to your application’s model (either a particular class or aspect of your data), your best bet is to use the Rails console that we looked at earlier in this chapter. Type console from the script directory to launch the console. Once inside, you can load the particular model that you’re interested in, and poke at it to reproduce and fix the problem.
- If the problem leans more towards something related to the user’s browser or session, you can add a breakpoint statement around the spot at which the problem occurs. With this in place, you can reload the browser and step through your application’s code using the breakpointer command line tool to explore variable content or to execute Ruby statements manually.
We’ll be covering all the gory details of debugging in Chapter 11, Debugging, Testing, and Benchmarking.
A GUI Tool for MySQL
The MySQL command line that we’ve been using in this chapter is one way to maintain your database structure and the data that it contains. But working in a command line client can definitely be overwhelming, complex, and tedious — especially when you’re just taking your first steps with databases and don’t know your way around!
A GUI tool available for use with MySQL that’s worth a mention is the MySQL Query Browser. Published by MySQL AB (the makers of MySQL), the MySQL Query Browser is a free, cross-platform tool that is currently available for Windows, Linux, and Mac OS X. The MySQL Query Browser is available for download from http://dev.mysql.com/downloads/query-browser/. Unfortunately there is no binary install package for OS X 10.3 or earlier; CocoaMySQL is a good alternative.
Installing MySQL Query Browser is a straightforward process on most platforms:
- Windows – A binary installer exists for Windows — launch the installer and select the default options for each step in the wizard.
- Mac OS X – A binary installer exists for the Mac as well. Mount the disk image and drag the application icon to your Applications folder.
- Linux – A package exists for most distributions of Linux; install the application using your distribution’s package manager.
Figure 4.7. The MySQL Query Browser connection screen
The MySQL Query Browser can be used to perform queries against your database. You can also use it to alter your database structure by creating and modifying databases and tables. Figure 4.7 shows the connection screen.
The connection details to use are identical to the ones we used earlier, when we configured Rails to connect to our database in the config/database.yml file. Assuming that you haven’t changed your MySQL configuration since then, enter localhost into the Hostname field and root for the Username. Now hit Connect.
Once you’re connected, you should be greeted by a window similar to the one shown in Figure 4.8.
Figure 4.8. MySQL Query Browser’s Query window
At the top of the main window is a text field in which you can type database queries. The pull-out tab on the right-hand side lists the databases to which you can connect. There’s even a function and syntax reference.
The MySQL Query Browser displays the table schema of the stories table exactly as we’ve created it, with the added benefit that we can alter it with just a mouse click. By clicking the + button at the bottom of the column list, you can add a column; clicking the – button removes the currently selected column. Pretty simple, isn’t it?
Exploring every feature of the query browser is definitely beyond the scope of this book, but there is one more thing I’d like to show you: the Table Editor, which is shown in Figure 4.9.
To launch the Table Editor, first expand the shovell_development database by clicking on the triangle next to the database’s name. This will list all of the tables in the database. Currently, there should only be one: the
stories table that we created earlier. Now right-click (Control-click on a Mac) on the table that you want to edit, and select Edit Table from the menu that appears.
Figure 4.9. The MySQL Table Editor
The Table Editor allows you to edit existing tables and add new tables, all using a nice GUI interface. I’m sure you’ll agree this is a much friendlier experience than having to battle with the cryptic command line tool.
That’s it for the MySQL Query Browser — we’ll revisit it briefly in Chapter 5, Models, Views, and Controllers, but feel free to close the application now.
In this chapter, we peeled back some of the layers that comprise the Ruby on Rails framework. By now you should have a good understanding of which parts of Rails perform particular roles in the context of an MVC architecture. It should also be reasonably clear how a request that’s made by a web browser is processed by a Rails application.
We looked at the different environments that Rails provides to address the different stages in the lifecycle of an application, and we created databases to support these environments. We also provided Rails with the necessary details to connect to our database.
We also had our first contact with real code, as we looked at the ActiveRecord models, ActionController controllers, and ActionView templates for our clone of digg.com, Shovell. We explored the topics of code generation, testing, and debugging, and we took a brief look at a GUI client that makes interacting with our MySQL database more convenient.
In the next chapter, we’ll build on all of this knowledge as we use the code generation tools to create actual models, controllers, and views for our Shovell application. It’s going to be a big one!
That’s it for this excerpt of Build Your Own Ruby On Rails Web Applications — but don’t forget that the downloadable PDF contains three more chapters than are included here. See the complete Table of Contents for the full details of what’s covered in this book.
If you enjoyed reading this post, you’ll love Learnable; the place to learn fresh skills and techniques from the masters. Members get instant access to all of SitePoint’s ebooks and interactive online courses, like Learning Ruby on Rails 3.