Rails 3 in Action ebook free download

IN ACTION

  Ryan Bigg Yehuda Katz M A N N I N G

  

Rails 3 in Action

  Rails 3 in Action RYAN BIGG YEHUDA KATZ M A N N I N G S HELTER

  I SLAND For online information and ordering of this and other Manning books, please visit he publisher offers discounts on this book when ordered in quantity. For more information, please contact

  Special Sales Department Manning Publications Co.

  20 Baldwin Road PO Box 261 Shelter Island, NY 11964 Email: orders@manning.com ©2012 by Manning Publications Co. All rights reserved.

  No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by means electronic, mechanical, photocopying, or otherwise, without prior written permission of the publisher.

  Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in the book, and Manning Publications was aware of a trademark claim, the designations have been printed in initial caps or all caps.

  Recognizing the importance of preserving what has been written, it is Manning’s policy to have the books we publish printed on acid-free paper, and we exert our best efforts to that end. Recognizing also our responsibility to conserve the resources of our planet, Manning books are printed on paper that is at least 15 percent recycled and processed without the use of elemental chlorine.

  Manning Publications Co. Development editor: Cynthia Kane

  20 Baldwin Road Copyeditors: Kevin Hobson, Linda Kern PO Box 261 Proofreader: Tiffany Taylor Shelter Island, NY 11964 Typesetter: Dottie Marsico

  Cover designer: Marija Tudor

  ISBN 978-1-935182-27-6 Printed in the United States of America 1 2 3 4 5 6 7 8 9 10 – MAL – 16 15 14 13 12 11

  v brief contents

  14

  11

  

  12

  

  13

  

  

  10

  15

  

  16

  

  17

  

  18

  

  

  1

  

  

  2

  

  3

  

  4

  5

  9

  

  6

  

  7

  

  8

  

  

  vii contents about the authors xxiii about the cover illustration xxiv

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  2.4

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  preface

  This book has been through quite the development process! It began in 2008 with Michael Ivey, Yehuda Katz, and Ezra Zygmuntowicz and was called Merb in Action. Since then it has changed name and hands a couple of times, winding up with people such as James Cox and the great Mike Gunderloy, the latter of whom is probably most famous for his work on Factsheet Five and many .NET books, not to mention being one of the founding members of the RailsBridge ( ) organization.

  Then, somehow, I became involved with this book. I received an email on a cold April morning in 2010 from Christina Rudloff at

  Manning asking if I would have any interest in joining the project. I was exceptionally excited! I had been writing short blog posts about Rails for years, and the idea of focusing that effort into writing a book made me extremely happy. Long story short: Yehuda Katz liked what he saw on my blog and wanted me to join the project. Working with Yehuda has been brilliant. He’s got to be one of the smartest and most patient people I have ever met.

  Shortly after receiving that initial email from Christina, I talked with another per- son from Manning, Michael Stephens, first via email and then very late at night over the phone (we are on different continents) about the project. I worked out the initial chapter layout, and I distinctly remember one thing that Michael asked me: “You know what you’re getting yourself into, right?” I thought “Sure, I’ve written blog posts before, how hard could it be?” and replied in much the same manner. How little did I know!

  Since then, I have learned a lot about the book-writing process. For starters, it involves a lot more than just the two people and the publishing company on the front

  xv cover. It also takes a very long time to write a book. This book has been my life for the past year and a bit. I’ve spent many weekends, mornings before work, and evenings after work (and way too often, time even in my dreams) writing chapters for this book. I’ve talked about it (perhaps too much) as well. It’s become such a running joke among people I know that when I’m introduced, they ask, “Do you know he’s writing a book?”

  Writing is sometimes easy, but other times it can be a struggle to come up with any- thing at all. There have been bad days, sure, but the good days outnumber those mas- sively. The feeling of achievement you get when you finish a chapter, or even a section, is awesome. Receiving positive feedback from people has been a huge boon to com- pleting this book.

  Now, in 2011, the book is finally done, and what an amazing feeling that is! I’d like to think that it offers a unique perspective on developing a full Ruby on Rails applica- tion from scratch in the same (or at least, similar) manner that people are developing Rails applications at this time. It’s also the first book to cover the latest features of Rails found in version 3.1.

  R YAN B

  IGG

  acknowledgments

  This has been an amazing process, full of amazing people. A large portion of this book would not have been possible without the support of my employer, Mikel Lind- saar, and company, RubyX, allowing me to take time off to write the book. The sup- port of the community at large has also been enormous in helping me complete this book. Winning the Ruby Hero award at RailsConf, partially due to my work on this very book, was the highlight of my career so far. After I won the award, Mikel also pro- vided me with a new laptop at no expense to replace my previous one that was three years old. Bloody champion!

  Of course, a lot of this wouldn’t have been as easy if it wasn’t for the Rails Core Team’s valiant efforts on their maintenance of the framework over the years and their constant focus on improving people’s lives on an almost daily basis. Also there are Yehuda Katz, Carl Lerche, and André Arko to thank for their work on an important part of developing not only Rails applications, but also Ruby libraries such as Bundler and Thor. These people are my idols, and I love them dearly.

  Through a Rails-based review system called Twist that I built myself over a single day, I’ve collected more than 1,200 notes from people from around the world who have been reviewing the book as I have been writing it. A special mention goes to the three people who’ve left the most notes in Twist: Roy Hacker, Deryl Doucette, and Peter Ley. An almost-as-special mention goes to the 33 other people who’ve also left notes. Without your help, this book wouldn’t be half as brilliant as it is today.

  Also thanks to Tim McEwan for the ideas for the engines chapter, Chris Darroch for an initial read-through of the first chapters, and Rob Zolkos for helping with some

  xvii gnarly ePub Ruby and XLST code. And yes, thanks to Andrew Snow for assisting with a difficult moral problem in chapter 16 at Railscamp in June 2011.

  In addition to those who’ve been leaving notes in Twist, there are the people at Manning. First, thanks to Christina Rudloff for the initial contact and Michael Ste- phens for the late-night chats and management of the process. Candace Gillhooley and Nick Chase have also been enormously helpful.

  Cynthia Kane, my development editor at Manning, is particularly special. Her job was to tell me when I was doing things wrong, such as not segueing between sections or making the text flow too fast, and to leave me notes such as “FIGURE!!!” when I needed an image to go along with the text. Our almost weekly catch-ups were well worthwhile; it was great always having someone there, prodding me for more content and talking through the process. Marjan Bace, fearless leader of Manning Publica- tions, should also be credited for supporting this project for as long as it has been around.

  The production team at Manning, including Troy Mott, has been great throughout this process too. The extreme focus they’ve shown in finishing this book is stunning. I also need to mention the wonderful work by Doug Warren in the final technical proofing of the book, as well as Manning’s copyeditors, who touched up basically every single paragraph in the book.

  Special thanks to the reviewers who took time out of their busy schedules to pro- vide feedback on the manuscript at different stages during development. They include Jason Rogers, Craig Smith, Emmanuel Asante, Chad Moone, Dr. Jamie P. Fin- lay, Dave Nicolette, Grant Oladipo, Jean-Philippe Castro, Americo Savinon, Thomas Athanas, Chris Kelly, Greg Vaughn, Pete Helgren, Joshua R Cronemeyer, Peter Melo, Robby O’Connor, Philip Hallstrom, Curtis Miller, Patrick Peak, Anthony J. Topper, Brian Rose, Daniel Bretoi, Wesley Moxam, Jon Agnes, and David Workman

  Finally, my friends and family have been amazing throughout my entire life, all the way from my parents—who supported my career choice in Ruby on Rails and techni- cal writing, even though they paid for me to study Network Admin at TAFE and always told me that I should “get out the house more”—to my current housemate, who accepts that we don’t see much of each other (or at least I think so). You’re all won- derful people, and I hope now that the book is over I will see more of you. I would list you all here if only it didn’t require this book to be printed in a multivolume series.

  R YAN B

  IGG Rails 3 in Action is a long-time coming. To give you some perspective, the book was

  originally called Merb in Action, and it managed a perpetual beta through the Merb merge, the release of Rails 3.0, and is finally ready just in time for Rails 3.1.

  I can say with confidence that Rails 3 in Action would not exist without the hard, tireless work of Ryan Bigg. It was Ryan’s idea to focus the book around real-world test- ing from the ground up, and it makes Rails 3 in Action the first book for Rails practitio- ners that teaches Rails the way professional Rails developers do it.

  Since we merged Merb with Rails, I have had the benefit of not insignificant sup- port from friends and family, who helped keep me on course in the long process that eventually delivered Rails 3.0. I want to especially call out Aaron Patterson, José Valim, Santiago Pastorino, and Xavier Noria, who stepped up and brought life back to a com- munity that was starting to show signs of age by the time Rails 2.3 hit the shelves. And Carl Lerche, who helped me keep focus on doing things right, even when it was tempting not to.

  Finally, I would be remiss if I didn't thank my wife, Leah, who has been there for me through the amazing trajectory of my development career, through good times and bad. Without her, I would have given up long ago.

  Y EHUDA K ATZ

  about this book

  Ruby on Rails is a leading web application framework built on top of the fantastic Ruby programming language. Both the language and the framework place an extreme emphasis on having a principle of least surprise and getting out of the way of the developers using it.

  Ruby on Rails has been growing at a rapid pace, with large internet companies such as Yellow Pages and Groupon using it for their core functionality. With the latest release of Rails, version 3.1, comes a set of changes that improve the already brilliant framework that has been constructed over the past seven years. The fantastic commu- nity around the framework has also been growing at a similar pace.

  This book is designed to take you through developing a full-featured Rails applica- tion from step one, showing you exactly how professionals in the real world are devel- oping applications right now.

  Who should read this book

  This book is primarily for those who are looking to begin working with the Ruby on Rails framework and who have some prior experience with Ruby, although that is not entirely necessary.

  Later chapters, such as chapter 13, “Designing an API,” chapter 17, “Engines,” and

  chapter 18, “Rack-based applications,” delve into more advanced topics, so these chap- ters are suitable for people who already have a foundation with Rails and are looking to expand their skillset a little further.

  If you’re looking for a book that teaches you the same practices that are used in the real world, then this is the book you are looking for.

  xx

  Roadmap

  Chapter 1 introduces the Ruby on Rails framework and begins to show how you can develop the beginnings of an application. Chapter 2 shows off test-driven development and behavior-driven development, which are two core concepts in this book and for developing Rails applications. By testing the code you write, you can be assured that it’s always working that way.

  Chapters 3 and 4 discuss the application you develop in this book—a project-man- agement app of sorts—and delve into the core concepts of a Rails application. They also look at developing the first core features of your application.

  Chapter 5 begins an introduction to nested resources, building on top of the fea- tures developed in the previous two chapters. Chapter 6 introduces authentication, requiring users to sign in to the application before they can perform certain tasks. Chapter 7 builds on the work in chapter 6 by adding new areas of the application that are accessible only to users with a certain flag set in the database. You also use namespaces for the first time.

  Chapter 8 builds on the basic authorization created in chapter 7, fleshing it out into something neater and more scalable. In chapter 9, you learn about file uploading using the Paperclip gem. In this chap- ter you also learn about testing parts of your application that use JavaScript and about CoffeeScript, a neater language that compiles down to JavaScript.

  Chapter 10 builds not one but two new features for the application, adding the ability to comment on a ticket as well as track the ticket’s lifecycle through varying states.

  In chapter 11, you add a feature that lets users assign tags to tickets so they can be easily grouped. You also add a feature to allow users to search for tickets matching a certain state or tag, or both.

  Chapter 12 begins our foray into dealing with email in a Rails application. You’ll see not only how to send email but also how to receive messages and parse them into meaningful data in your application.

  Chapter 13 involves creating an API for the project resources in an application that provide other applications with a standardized way to access your application’s data. We also look at token-based authentication and how to create multiple versions of an API.

  In chapter 14, you deploy the application to an Ubuntu box and set it up to act like a normal web server using a RubyGem called Passenger and a web server called nginx. In chapter 15, you create a “nice to have” feature: the ability to sign up or sign in using either Twitter or GitHub. When this is complete, people are no longer required to provide you with an email and password when they sign up; instead, they can use GitHub and Twitter as authentication providers. By chapter 16, your application is all grown up and needs to handle any kind of performance issues it encounters. We cover basic performance enhancements, such as pagination, database indexing, and page and fragment caching.

  Chapter 17 introduces a new feature for Rails 3: engines. You develop one of your own from scratch—a forum system—and then integrate it with the existing application. Chapter 18 delves into the depths of Rack, explaining how Rack applications are made and can be tied into Rails. The chapter also explains, and contains examples of, middleware being used in Rails.

  Code conventions and downloads

  Code conventions in the book follow the style of other Manning books in the In Action series. All code in listings and in text appears in a monospaced font like this to sepa- rate it from ordinary text. In some cases, the original source code has been reformat- ted to fit on the pages. In general, the original code was written with page-width limitations in mind, but sometimes you may find a slight formatting difference between the code in the book and that provided in the source download. In a few rare cases, where long lines could not be reformatted without changing their meaning, the book listings contain line-continuation markers. Code annotations accompany many of the listings, highlighting important concepts. In many cases, numbered bullets link to explanations that follow in the text.

  Source code for all the working examples in this book is available for download from the publisher’s website at

  Author Online

  The purchase of Rails 3 in Action includes free access to a private forum run by Man- ning Publications where you can make comments about the book, ask technical ques- tions, and receive help from the authors and other users. To access and subscribe to the forum, point your browser to , and click the Author Online link. This page provides information on how to get on the forum once you are registered, what kind of help is available, and the rules of conduct in the forum.

  Manning’s commitment to our readers is to provide a venue where a meaningful dialogue between individual readers and between readers and the authors can take place. It’s not a commitment to any specific amount of participation on the part of the authors, whose contribution to the book’s forum remains voluntary (and unpaid). We suggest you try asking the authors some challenging questions, lest their interest stray!

  The Author Online forum and the archives of previous discussions will be accessi- ble from the publisher’s website as long as the book is in print.

  about the authors

  R YAN B

  IGG has been developing Ruby on Rails since version 1.2 and can be found

  helping out the community by answering questions on IRC or StackOverflow or writ- ing documentation. He currently works for a web consultancy based in Sydney called RubyX. Y EHUDA K ATZ is well known not only for his work on this third version of Ruby on Rails, but also for other web-related projects such as jQuery, Bundler, Merb, and SproutCore. He currently works for Strobe in San Francisco as a lead developer on SproutCore and is the coauthor of Manning’s jQuery in Action, Second Edition.

  xxiii

  about the cover illustration

  The figure on the cover of Rails 3 in Action is captioned “A Soldier.” The illustration is taken from a nineteenth-century edition of Sylvain Maréchal’s four-volume compen- dium of regional and military dress customs published in France. Each illustration is finely drawn and colored by hand. The rich variety of Maréchal’s collection reminds us vividly of how culturally apart the world’s towns and regions were just 200 years ago. Isolated from each other, people spoke different dialects and languages. In the streets or in the countryside, it was easy to identify where they lived and what their trade or station in life was just by their dress.

  Dress codes have changed since then and the diversity by region, so rich at the time, has faded away. It is now hard to tell apart the inhabitants of different conti- nents, let alone different towns or regions. Perhaps we have traded cultural diversity for a more varied personal life—certainly for a more varied and fast-paced technolog- ical life.

  At a time when it is hard to tell one computer book from another, Manning cele- brates the inventiveness and initiative of the computer business with book covers based on the rich diversity of regional life of two centuries ago, brought back to life by Maréchal’s pictures.

  xxiv

  Ruby on Rails, the framework This chapter covers  Exploring Ruby on Rails  Building the foundations of a Ruby on Rails app  Working with the scaffold generator

  Welcome aboard! It’s great to have you with us on this journey through the world of Ruby on Rails. Ruby on Rails is known throughout the lands as a powerful web framework that helps developers rapidly build modern web applications. In partic- ular, it provides lots of niceties to help you in your quest to develop a full-featured real-world application and be happy doing it. Great developers are happy develop- ers. There’s much more to the Rails world than might appear at first glance, but not overwhelmingly too much. And what a first glance! Oh, you two haven’t met? Well, time for some introductions then!

  1

  Ruby on Rails, the framework

1.1 What is Ruby on Rails?

  Ruby on Rails is a framework built on the Ruby language, hence the name Ruby on Rails. The Ruby language was created back in 1993 by Yukihiro “Matz” Matsumuto of Japan. Ruby was released to the general public in 1995. Since then, it has earned both a reputation and an enthusiastic following for its clean design, elegant syntax, and wide selection of tools available in the standard library and via a package management system called RubyGems. It also has a worldwide community and many active contribu- tors constantly improving the language and the ecosystem around it.

  Ruby on Rails was created in 2004 by David Heinemeier Hansson during the devel- opment of 37signals’ flagship product: Basecamp. When Rails was needed for other 37signals projects, the team extracted the Rails code from it, crafted the beginnings of

  1

  the framework, and released it as open source under the MIT license. Since then, Ruby on Rails has quickly progressed to become one of the leading web development frameworks. This is in no small part due to the large community surrounding it who are constantly working on submitting patches to add new features or to fix existing bugs. Version 3 of this framework indicates yet another significant milestone in the project’s history and introduces some new concepts, but won’t leave those already familiar with the framework in the dark. The latest version of Rails is the primary focus of this book.

1.1.1 Benefits

  Ruby on Rails allows for rapid development of applications by using a concept known as convention over configuration. When you begin writing a Ruby on Rails application, you run an application generator, which creates a basic skeleton of directories and files for your application. These files and directories provide categorization for pieces of your code, such as the app/models directory for containing files that interact with the database and the public/images directory for images. Because all of this is already there for you, you won’t be spending your time configuring the way your application is laid out. It’s done for you.

  How rapidly can you develop a Ruby on Rails application? Take the annual Rails

  Rumble event. This event aims to bring together small teams of one to four developers

  2

  around the world to develop Ruby on Rails applications in a 48-hour period. Using

  3 Rails, these teams can deliver amazing web applications in just two days. Another

  great example of rapid development of a Rails application is the 20-minute blog

  4

  screencast recorded by Yehuda Katz. This screencast takes you from a no-application state to having a basic blogging and commenting system.

  Ruby on Rails affords you a level of productivity unheard of in other web frame- 1 works because every Ruby on Rails application starts out the same way. The similarity 2 The MIT 3 And now other Ruby-based web frameworks, such as Sinatra.

  

To see an example of what has come out of previous Rails Rumbles, take a look at their alumni archive:

4

  20-minute blog screencast: http://vimeo.com/10732081.

  

What is Ruby on Rails?

  between the applications is so close that the paradigm shift between different Rails applications is not tremendous. If and when you jump between Rails applications, you don’t have to relearn how it all connects—it’s mostly the same.

  The core features of Rails are a conglomerate of many different parts called Rail- ties (when said aloud it rhymes with “bowties”), such as Active Record, Active Support,

5 Action Mailer, and Action Pack. These different Railties provide a wide range of meth-

  ods and classes that help you develop your applications. They prevent you from per- forming boring, repetitive tasks—such as coding how your application hooks into your database—and let you get right down to writing valuable code for your business.

  Ever wished for a built-in way of writing automated tests for your web application? Ruby on Rails has you covered with Test::Unit, part of Ruby’s standard library. It’s incredibly easy to write automated test code for your application, as you’ll see throughout this book. Test::Unit saves your bacon in the long term, and that’s a fantas- tic thing. We touch on Test::Unit in the next chapter before moving on to RSpec and Cucumber, two other test frameworks that are preferred over Test::Unit and a little easier on the eyes too.

  In addition to testing frameworks, the Ruby community has produced several high- quality libraries (called RubyGems, or gems for short) for use in your day-to-day devel- opment with Ruby on Rails. Some of these libraries add additional functionality to Ruby on Rails; others provide ways to turn alternative markup languages such as Mark- down and Textile into HTML. Usually, if you can think it, there’s a gem out there that will help you do it.

  Noticing a common pattern yet? Probably. As you can see, Ruby on Rails (and the great community surrounding it) provides code that performs the trivial application tasks for you, from setting up the foundations of your application to handling the delivery of email. The time you save with all these libraries is immense! And because the code is open source, you don’t have to go to a specific vendor to get support. Any- body who knows Ruby can help you if you’re stuck.

1.1.2 Common terms

  You’ll hear a few common Ruby on Rails terms quite often. This section explains what they mean and how they relate to a Rails application.

  MVC

  The Model-View-Controller (MVC) paradigm is not unique to Ruby on Rails but pro- vides much of the core foundation for a Ruby on Rails application. This paradigm is designed to keep the logically different parts of the application separate while provid- ing a way for data to flow between them.

  In applications that don’t use MVC, the directory structure and how the different 5 parts connect to each other is commonly left up to the original developer. Generally,

  

Railties share the same version number as Rails, which means when you’re using Rails 3.1, you’re using the

3.1 version of the Railtie. This is helpful to know when you upgrade Rails because the version number of the

installed Railties should be the same as the version number of Rails.

  Ruby on Rails, the framework

  this is a bad idea because different people have different opinions on where things should go. In Rails, a specific directory structure makes all developers conform to the same layout, putting all the major parts of the application inside an app directory. This app directory has three main subdirectories: models, controllers, and views.

  Domain logic—how the records in your database are retrieved—is kept in models.

  In Rails applications, models define the code that interacts with the database’s tables to retrieve and set information in them. Domain logic also means things such as vali- dations or particular actions to perform on the data.

  Controllers interact with the models to gather information to send to the view. They call methods on the model classes, which can return single objects representing rows in the database or collections (arrays) of these objects. Controllers then make these objects available to the view through instance variables.

  Views display the information gathered by the controller, by referencing the instance variables set there, in a user-friendly manner. In Ruby on Rails, this display is done by default with a templating language known as Embedded Ruby (ERB). ERB allows you to embed Ruby (hence the name) into any kind of file you wish. This tem- plate is then preprocessed on the server side into the output that’s shown to the user.

  The assets, helpers, and mailers directories aren’t part of the MVC paradigm, but they are important parts of Rails. The assets directory is for the static assets of the application, such as JavaScript files, images, and Cascading Style Sheets (CSS) for mak- ing the application look pretty. We look more closely at this in chapter 3.

  The helpers directory is a place to put Ruby code (specifically, modules) that pro- vides helper methods for just the views. These helper methods can help with complex formatting that would otherwise be messy in the view or is used in more than one place.

  Finally, mailers is a home for the classes of your application that deal with sending email. In previous versions of Rails, these classes were grouped with models but have since been given their own home. We look at them in chapter 11.

  REST

  MVC in Rails is aided by REST, a routing paradigm. Representational State Transfer (REST) is the convention for routing in Rails. When something adheres to this conven- tion, it’s said to be RESTful. Routing in Rails refers to how requests are routed within the application itself. You benefit greatly by adhering to these conventions, because Rails provides a lot of functionality around RESTful routing, such as determining where a form can, or will, send to.

1.1.3 Rails in the wild

  A question sometimes asked by people new to Rails is, “Is Rails ready?” Of course it is! The evidence is stacked mightily in Rails’ favor with websites such as Twitter, Yellow

  6 6 Pages, and of course Basecamp, serving millions and millions of page requests daily.

  

Some of the more well-known applications that run on Ruby on Rails can be found at

  

Developing your first application

  If any site is a testament to the power of Ruby on Rails, Twitter is it. Even though Twitter suffered from scaling problems back in 2008 (due to its massive growth and other technological problems, not due to Rails), it is now the eleventh most popular website, according to Alexa, and is exceptionally stable.

  Another well-known site that runs Ruby on Rails is GitHub, a hosting service for Git repositories. This site was launched in February 2008 and is now the leading Git web-hosting site. GitHub’s massive growth was in part due to the Ruby on Rails com- munity quickly adopting it as their de facto repository hosting site. Now GitHub is home to over a million repositories for just about every programming language on the planet. It’s not exclusive to programming languages either; if it can go in a Git reposi- tory, it can go on GitHub. As a matter of fact, this book and its source code are kept on GitHub!

  Now that you know what other people have accomplished with this framework, let’s dive into creating your own application.

1.2 Developing your first application

  We covered the theory behind Rails and showed how quickly and easily you can develop an application. Now it’s your turn to get an application going.

1.2.1 Installing Rails

  To get started, you must have these three things installed:

  

  Ruby

  

  RubyGems

  

  Rails If you’re on a UNIX-based system (Linux or Mac), we recommend you use RVM ) to install Ruby and RubyGems. It is the preferred solution of the community because it works so simply. Installing from a package man-

  7

  agement system such as Ubuntu’s Aptitude has been known to be broken. After installing RVM, you must run this command to install a 1.9.2 version of Ruby:

  rvm install 1.9.2

  To use this version of Ruby, you would need to use rvm use 1.9.2 every time you wished to use it or else set up a .rvmrc file in the root of your project, which is explained on the RVM site in great detail. Alternatively, you can set this version of Ruby as the default with the command rvm use --default 1.9.2, and use rvm use system if you ever want to swap back to the system-provided Ruby install if you have one.

  If you’re on Windows, you can’t use RVM and you can’t use a 1.9.* version of Ruby, but that’s okay. Rails 3 works with Ruby 1.8 versions of Rails too. We would recom- mend the use of the Rails Installer program ( from Engine 7 Yard, or installing the Ruby 1.8.7-p352 binary from ruby-lang.org as an alternative.

  

Broken Ubuntu Ruby explained here

  Ruby on Rails, the framework

  Next, you need to install the rails gem. The following command installs both Rails and its dependencies. If you’re using the Rails installer you will not need to run this command because Rails will already be installed:

  gem install rails -v 3.1.0

  1.2.2 Generating an application

  With Rails now installed, to generate an application, you run the rails command and pass it the new argument and the name of the application you want to generate:

  things_i_bought. When you run this command, it creates a new directory called

  things_i_bought, which is where all your application’s code will go. You can call your application anything you wish, but it can’t be given the same name as a reserved word in Rails. For example, you wouldn’t call your application rails because it defines a Rails constant, which is internal to Rails, and the two constants would clash.

  The application that you’re going to generate will be able to record purchases you have made. You can generate it using this command:

  rails new things_i_bought

  The output from this command may seem a bit overwhelming at first, but rest assured: it’s for your own good. All of the directories and files generated here provide the building blocks for your application, and you’ll get to know each of them as we prog- ress. For now, let’s get rolling and learn by doing, which is the best way of learning.

  1.2.3 Starting the application

  To get the server running, you must first change into the newly created application’s directory and then run these commands to start the application server:

  cd things_i_bought bundle install rails server The bundle install command installs all the gems required for your application.

  This is explained in further detail in chapter 3.

  This starts a web server on your local address on port 3000 using a Ruby standard library web server known as WEBrick. It will say it’s “starting in development on

   ,” which indicates to you that the server will be available on port

  8

  3000 on all network interfaces of this machine. To connect to this server, go to

   in your favorite browser. You’ll see the “Welcome aboard” page, which is so famous in Rails (see figure 1.1).

  If you click About Your Application’s Environment, you’ll find your Ruby, Ruby- Gems, Ruby on Rails, and Rack versions and other environmental data. One of the 8 things to note here is that the output for Environment is Development. Rails provides

  This is what the 0.0.0.0 address represents. It is not an actual address, so to speak, and so localhost or 127.0.0.1 should be used.

  

Developing your first application

Figure 1.1 Welcome aboard! three environments for running your application: development, test, and production.

  How your application functions can depend on the environment in which it is run- ning. For example, in the development environment, classes are not cached; so if you make a change to a class when running an application in development mode, you don’t need to restart the server, but the same change in the production environment would require a restart.

1.2.4 Scaffolding

  To get started with this Rails application, you generate a scaffold. Scaffolds in Rails pro- vide a lot of basic functionality but are generally not used for full-scale development because you may want something more customized, in which case you’d build it your- self. But for this example of what Rails can do, let’s generate a scaffold by running this command:

  rails generate scaffold purchase name:string cost:float When you used the rails command earlier, it generated an entire Rails application.

  You can use this command inside of an application to generate a specific part of the application by passing the generate argument to the rails command, followed by what it is you want to generate.

  Ruby on Rails, the framework

  The scaffold command generates a model, a controller, and views based on the name passed after scaffold in this command. These are the three important parts needed for your purchase tracking. The model provides a way to interact with a data- base. The controller interacts with the model to retrieve and format its information and defines different actions to perform on this data. The views display the informa- tion from the controller in a neat format.

  Everything after the name for the scaffold are the fields for the database table and the attributes for the objects of this scaffold. Here you tell Rails that the table for your

  9

  purchase scaffold will contain name and cost fields, which are a string and a float. To create this table, the scaffold generator generates what’s known as a migration. Let’s have a look at what migrations are.

1.2.5 Migrations

  Migrations are used in Rails as a form of version control for the database, providing a way to implement incremental changes to the schema of the database. Each migration is timestamped right down to the second, which provides you (and anybody else devel- oping the application with you) an accurate timeline of your database. When two developers are working on separate features of an application and both generate a new migration, this timestamp will stop them from clashing. Let’s open the only file in db/migrate now and see what it does. Its contents are shown in the following listing.

  Listing 1.1 db/migrate/[date]_create_purchases.rb class CreatePurchases < ActiveRecord::Migration def self.up create_table :purchases do |t| t.string :name t.float :cost t.timestamps end end def self.down drop_table :purchases end end

  Migrations are Ruby classes that inherit from ActiveRecord::Migration. Inside the class, two class methods are defined: up and down. Inside the up method is the code you want to be run when you run the migration, and inside the down method is the code that runs when you roll the migration back.

  Inside both of these methods you use database-agnostic commands to create and 9 drop a table. In the up method, you create a table and specify the fields you want in

  

Usually you wouldn’t use a float for storing monetary amounts because it can lead to incorrect-rounding

errors. Generally, you store the amount in cents as an integer and then do the conversion back to a full dollar

amount. This example uses a float because it’s easier to not have to define the conversion at this point.

  

Developing your first application

  that table by calling methods on the t block variable. The string and float methods

  10

  create fields of those particular types on any Rails-compatible database system. You specified these fields when you used the scaffold command. The timestamps method is special; it creates two fields called created_at and updated_at, which have their values set when records are created and updated automatically by Rails.

  To run the migration, type this command into the console:

  rake db:migrate