Ruby on Rails教程: From Zero to Deploy
- 1.1. Introduction
- 1.2. Up and Running
- 1.3. Version Control with Git
- 1.4. Deploying
- 1.5. Conclusion
Welcome toRuby on Rails™Tutorial. The goal of this book is to be the best answer to the question, “If I want to learn web development with Ruby on Rails, where should I start?” By the time you finish theRails Tutorial, you will have all the skills you need to develop and deploy your own custom web applications with Rails. You will also be ready to benefit from the many more advanced books, blogs, and screencasts that are part of the thriving Rails educational ecosystem. Finally, since theRails Tutorialuses Rails 3, the knowledge you gain here represents the state of the art in web development. (The most up-to-date version of theRails Tutorialcan be found on the book’s website athttp://railstutorial.org; if you are reading this book offline, be sure to check the online version of the Rails Tutorial book athttp://railstutorial.org/bookfor the latest updates.)
Note that the goal of this book isnotmerely to teach Rails, but rather to teachweb development with Rails, which means acquiring (or expanding) the skills needed to develop software for the World Wide Web. In addition to Ruby on Rails, this skillset includes HTML and CSS, databases, version control, testing, and deployment. To accomplish this goal,Rails Tutorialtakes an integrated approach: You will learn Rails by example by building a substantial sample application from scratch. As Derek Sivers notes in the foreword, this book is structured as a linear narrative, designed to be read from start to finish. If you are used to skipping around in technical books, taking this linear approach might require some adjustment, but I suggest giving it a try. You can think of theRails Tutorialas a video game where you are the main character and where you level up as a Rails developer in each chapter. (The exercises are the minibosses.)
In this first chapter, we’ll get started with Ruby on Rails by installing all the necessary software and by setting up our development environment (Section 1.2). We’ll then create our first Rails application, called (appropriately enough)first_app. TheRails Tutorialemphasizes good software development practices, so immediately after creating our fresh new Rails project we’ll put it under version control with Git (Section 1.3). And, believe it or not, in this chapter we’ll even put our first app on the wider web bydeployingit to production (Section 1.4).
In Chapter 2, we’ll make a second project, whose purpose is to demonstrate the basic workings of a Rails application. To get up and running quickly, we’ll build thisdemo app(calleddemo_app) using scaffolding (Box 1.1) to generate code; since this code is both ugly and complex, Chapter 2 will focus on interacting with the demo app through itsURIs(sometimes calledURLs)1using a web browser.
The rest of the tutorial focuses on developing a single largesample application(calledsample_app), writing all the code from scratch. We’ll develop the sample app usingtest-driven development(TDD), getting started in Chapter 3 by creating static pages and then adding a little dynamic content. We’ll take a quick detour in Chapter 4 to learn a little about the Ruby language underlying Rails. Then, in Chapter 5 through Chapter 9, we’ll complete the foundation for the sample application by making a site layout, a user data model, and a full registration and authentication system. Finally, in Chapter 10 and Chapter 11 we’ll add microblogging and social features to make a working example site.
The final sample application will bear more than a passing resemblance to a certain popular social microblogging site—a site that, coincidentally, was also originally written in Rails. Although of necessity our efforts will focus on this specific sample application, the emphasis throughout theRails Tutorialwill be on general principles, so that you will have a solid foundation no matter what kinds of web applications you want to build.
1.1. Introduction
Since its debut in 2004, Ruby on Rails has rapidly become one of the most powerful and popular frameworks for building dynamic web applications. Everyone from scrappy startups to huge companies have used Rails: 37signals, GitHub, Shopify, Scribd, Twitter, LivingSocial, Groupon, Hulu, the Yellow Pages—the list of sites using Rails goes on and on. There are also many web development shops that specialize in Rails, such as ENTP, thoughtbot, Pivotal Labs, and Hashrocket, plus innumerable independent consultants, trainers, and contractors.
是什么让Rails如此之大?首先,Ruby on Rails is 100 percent open-source, available under the permissive MIT License, and as a result it also costs nothing to download or use. Rails also owes much of its success to its elegant and compact design; by exploiting the malleability of the underlying Ruby language, Rails effectively creates a domain-specific language for writing web applications. As a result, many common web programming tasks—such as generating HTML, making data models, and routing URIs—are easy with Rails, and the resulting application code is concise and readable.
Rails also adapts rapidly to new developments in web technology and framework design. For example, Rails was one of the first frameworks to fully digest and implement the REST architectural style for structuring web applications (which we’ll be learning about throughout this tutorial). And when other frameworks develop successful new techniques, Rails creator David Heinemeier Hansson and the Rails core team don’t hesitate to incorporate their ideas. Perhaps the most dramatic example is the merger of Rails and Merb, a rival Ruby web framework, so that Rails now benefits from Merb’s modular design, stable API, and improved performance.
最后,从异常enthusia Rails好处stic and diverse community. The results include hundreds of open-source contributors, well-attended conferences, a huge number of plugins and gems (self-contained solutions to specific problems such as pagination and image upload), a rich variety of informative blogs, and a cornucopia of discussion forums and IRC channels. The large number of Rails programmers also makes it easier to handle the inevitable application errors: The “Google the error message” algorithm nearly always produces a relevant blog post or discussion-forum thread.
1.1.1. Comments for Various Readers
TheRails Tutorialcontains integrated tutorials not only for Rails, but also for the underlying Ruby language, the RSpec testing framework, HTML, CSS, a small amount of JavaScript, and even a little SQL. This means that, no matter where you currently are in your knowledge of web development, by the time you finish this tutorial you will be ready for more advanced Rails resources, as well as for the more systematic treatments of the other subjects mentioned. It also means that there’s alotof material to cover; if you don’t already have experience programming computers, you might find it overwhelming. The comments below contain some suggestions for approaching theRails Tutorialdepending on your background.
All readers:One common question when learning Rails is whether to learn Ruby first. The answer depends on your personal learning style and how much programming experience you already have. If you prefer to learn everything systematically from the ground up, or if you have never programmed before, then learning Ruby first might work well for you, and in this case I recommendBeginning Rubyby Peter Cooper. On the other hand, many beginning Rails developers are excited about makingwebapplications, and would rather not slog through a 500-page book on pure Ruby before ever writing a single web page. In this case, I recommend following the short interactive tutorial at TryRuby,2and then optimally do the free tutorial at Rails for Zombies3to get a taste of what Rails can do.
Another common question is whether to use tests from the start. As noted in the introduction, theRails Tutorial使用测试驱动开发(也称为test-first development), which in my view is the best way to develop Rails applications, but it does introduce a substantial amount of overhead and complexity. If you find yourself getting bogged down by the tests, I suggest either skipping them on a first reading or (even better) using them as a tool to verify your code’s correctness without worrying about how they work. This latter strategy involves creating the necessary test files (calledspecs) and filling them with the test codeexactlyas it appears in the book. You can then run the test suite (as described in Chapter 5) to watch it fail, then write the application code as described in the tutorial, and finally re-run the test suite to watch it pass.
Inexperienced programmers:TheRails Tutorialis not aimed principally at beginning programmers, and web applications, even relatively simple ones, are by their nature fairly complex. If you are completely new to web programming and find theRails Tutorialtoo difficult, I suggest learning the basics of HTML and CSS and then giving theRails Tutorialanother go. (Unfortunately, I don’t have a personal recommendation here, butHead First HTMLlooks promising, and one reader recommendsCSS: The Missing Manualby David Sawyer McFarland.) You might also consider reading the first few chapters ofBeginning Rubyby Peter Cooper, which starts with sample applications much smaller than a full-blown web app. That said, a surprising number of beginners have used this tutorial to learn web development, so I suggest giving it a try, and I especially recommend theRails Tutorialscreencast series4to give you an “over-the-shoulder” look at Rails software development.
Experienced programmers new to web development:Your previous experience means you probably already understand ideas like classes, methods, data structures, and others, which is a big advantage. Be warned that if your background is in C/C++ or Java, you may find Ruby a bit of an odd duck, and it might take time to get used to it; just stick with it and eventually you’ll be fine. (Ruby even lets you put semicolons at the ends of lines if you miss them too much.) TheRails Tutorialcovers all the web-specific ideas you’ll need, so don’t worry if you don’t currently know aPUTfrom aPOST.
Experienced web developers new to Rails:You have a great head start, especially if you have used a dynamic language such as PHP or (even better) Python. The basics of what we cover will likely be familiar, but test-driven development may be new to you, as may be the structured REST style favored by Rails. Ruby has its own idiosyncrasies, so those will likely be new, too.
Experienced Ruby programmers:The set of Ruby programmers who don’t know Rails is a small one nowadays, but if you are a member of this elite group you can fly through this book and then move on toThe Rails 3 Wayby Obie Fernandez.
Inexperienced Rails programmers:You’ve perhaps read some other tutorials and made a few small Rails apps yourself. Based on reader feedback, I’m confident that you can still get a lot out of this book. Among other things, the techniques here may be more up-to-date than the ones you picked up when you originally learned Rails.
Experienced Rails programmers:This book is unnecessary for you, but many experienced Rails developers have expressed surprise at how much they learned from this book, and you might enjoy seeing Rails from a different perspective.
After finishing theRuby on Rails教程, I recommend that experienced programmers readThe Well-Grounded Rubyistby David A. Black, which is an excellent in-depth discussion of Ruby from the ground up, orThe Ruby Wayby Hal Fulton, which is also fairly advanced but takes a more topical approach. Then move on toThe Rails 3 Wayto deepen your Rails expertise.
At the end of this process, no matter where you started, you should be ready for the many more intermediate-to-advanced Rails resources out there. Here are some I particularly recommend:
- RailsCasts by Ryan Bates: Excellent (mostly) free Rails screencasts
- PeepCode: Excellent commercial screencasts
- Code School: Interactive programming courses
- Rails Guides: Good topical and up-to-date Rails references
- RailsCasts by Ryan Bates: Did I already mention RailsCasts? Seriously:RailsCasts.
1.1.2. “Scaling” Rails
Before moving on with the rest of the introduction, I’d like to take a moment to address the one issue that dogged the Rails framework the most in its early days: the supposed inability of Rails to “scale”—i.e., to handle large amounts of traffic. Part of this issue relied on a misconception; you scale asite, not a framework, and Rails, as awesome as it is, is only a framework. So the real question should have been, “Can a site built with Rails scale?” In any case, the question has now been definitively answered in the affirmative: Some of the most heavily trafficked sites in the world use Rails. Actuallydoingthe scaling is beyond the scope of just Rails, but rest assured that ifyourapplication ever needs to handle the load of Hulu or the Yellow Pages, Rails won’t stop you from taking over the world.
1.1.3. Conventions in This Book
The conventions in this book are mostly self-explanatory. In this section, I’ll mention some that may not be.
Both the HTML and PDF editions of this book are full of links, both to internal sections (such as Section 1.2) and to external sites (such as the main Ruby on Rails download page).5
Many examples in this book use command-line commands. For simplicity, all command line examples use a Unix-style command line prompt (a dollar sign), as follows:
$echo"hello, world"hello, world
Windows users should understand that their systems will use the analogous angle prompt>:
C:\Sites> echo "hello, world" hello, world
On Unix systems, some commands should be executed withsudo, which stands for “substitute user do.” By default, a command executed withsudois run as an administrative user, which has access to files and directories that normal users can’t touch, such as in this example from Section 1.2.2:
$ sudo ruby setup.rb
Most Unix/Linux/OS X systems requiresudoby default, unless you are using Ruby Version Manager as suggested in Section 1.2.2; in this case, you would type this instead:
$ ruby setup.rb
Rails comes with lots of commands that can be run at the command line. For example, in Section 1.2.5 we’ll run a local development web server as follows:
$ rails server
As with the command-line prompt, theRails Tutorialuses the Unix convention for directory separators (i.e., a forward slash/). MyRails Tutorialsample application, for instance, lives in
/Users/mhartl/rails_projects/sample_app
On Windows, the analogous directory would be
C:\Sites\sample_app
The root directory for any given app is known as theRails root, but this terminology is confusing and many people mistakenly believe that the “Rails root” is the root directory for Rails itself. For clarity, theRails Tutorialwill refer to the Rails root as theapplication root, and henceforth all directories will be relative to this directory. For example, theconfigdirectory of my sample application is
/Users/mhartl/rails_projects/sample_app/config
The application root directory here is everything beforeconfig, that is,
/Users/mhartl/rails_projects/sample_app
For brevity, when referring to the file
/Users/mhartl/rails_projects/sample_app/config/routes.rb
I’ll omit the application root and simply writeconfig/routes.rb.
TheRails Tutorialoften shows output from various programs (shell commands, version control status, Ruby programs, etc.). Because of the innumerable small differences between different computer systems, the output you see may not always agree exactly with what is shown in the text, but this is not cause for concern.
Some commands may produce errors depending on your system; rather than attempt the Sisyphean task of documenting all such errors in this tutorial, I will delegate to the “Google the error message” algorithm, which among other things is good practice for real-life software development. If you run into any problems while following the tutorial, I suggest consulting the resources listed on the Rails Tutorial help page.6