Rails tutorial 2nd edition


















To accomplish this goal, the Ruby on Rails Tutorial takes an integrated approach: you will learn Rails by example by building a substantial sample application from scratch. 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 the Ruby on Rails Tutorial as 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. Fol- lowing the scaffolding approach risks turning you into a virtuoso script generator with little and brittle actual knowledge of Rails.

At each stage of developing the sample application, we will write small, bite-sized pieces of code—simple enough to understand, yet novel enough to be challenging. 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 contrac- tors.

What makes Rails so great? Rails also adapts rapidly to new developments in web technology and frame- work design. The comments below contain some suggestions for approaching the Rails Tu- torial depending on your background. On the other hand, many beginning Rails developers are excited about making web applications, and would rather not slog through a page book on pure Ruby before ever writing a single web page.

In this case, I recommend following the short interactive tutorial at Try Ruby,2 and then optionally do the free tutorial at Rails for Zombies3 to get a taste of what Rails can do. Another common question is whether to use tests from the start.

Inexperienced programmers: The Rails Tutorial is not aimed principally at beginning programmers, and web applications, even relatively simple ones, are by their nature fairly complex.

Experienced programmers new to web development: Your previous experi- ence means you probably already understand ideas like classes, methods, data structures, etc. Ruby even lets you put semicolons at the ends of lines if you miss them too much. Experienced web developers new to Rails: You have a great head start, es- pecially if you have used a dynamic language such as PHP or even better Python.

We need the methods from the Sessions helper in both places, so we have to include it explicitly. This session object makes the user id available from page to page by storing it in a cookie that expires upon browser close. On each page, the application could simply call. Because of the way Rails handles sessions, this process is secure; if a malicious user tries to spoof the user id, Rails will detect a mismatch based on a special session id generated for each session.

Next we fill in the resulting migration with the code from Listing 8. Now we have to decide what to use as a remember token. There are many mostly equivalent possibilities—essentially, any large random string will do just fine. This would work fine, but it has the downside that any hijacked sessions which involves copying the remember token and using it to sign in as the corresponding user would never expire.

Session hijacking was widely publicized by the Firesheep application, which showed that remember tokens at many high-profile sites were visible when connected to public Wi-Fi networks. The solution is to use site-wide SSL, as described in Section 7. Occasionally changing the remember token is still a security feature, though, since your remember token could still be obtained if the attacker has physical access to a computer where you are signed in.

This gives us sufficient flexibility to change the random string if we ever need to. The result appears in Listing 8. In other words,. The application code introduces several new elements. First, we add a callback method to create the remember token:. The Ruby way to accomplish this is to use the private keyword:. Note : If you are using Ruby 1. See Section Putting this all together yields the User model shown in Listing 8. Since the SecureRandom. The result, Listing 8.

We can use cookies as if it were a hash; each element in the cookie is itself a hash of two elements, a value and an optional expires date. This uses one of the convenient Rails time helpers, as discussed in Box 8. In that section, we added a palindrome? The cookie code in Listing 8. These are useful for upload validations, making it easy to restrict, say, image uploads to 5. Though it must be used with caution, the flexibility to add methods to built-in classes allows for extraordinarily natural additions to plain Ruby.

Indeed, much of the elegance of Rails ultimately derives from the malleability of the underlying Ruby language. This pattern of setting a cookie that expires 20 years in the future became so common that Rails added a special permanent method to implement it, so that we can simply write. Under the hood, using permanent causes Rails to set the expiration to The use of self is necessary in this context for the same essential reason noted in the discussion leading up to Listing 8.

Ruby has a special syntax for defining such an assignment function, shown in Listing 8. In other words, the code. Its one argument is the right-hand side of the assignment, in this case the user to be signed in. To avoid this problem, we can find the user corresponding to the remember token created by the code in Listing 8. Though at first it may seem mysterious, or equals is easy to understand by analogy. We start by noting a common idiom for changing a currently defined variable.

Many computer programs involve incrementing a variable, as in. Recalling the or operator seen in Section 4. Since nil is false in a boolean context, the first assignment is nil "the user" , which evaluates to "the user" ; similarly, the second assignment is "the user" "another user" , which also evaluates to "the user" —since strings are true in a boolean context, the series of expressions terminates after the first expression is evaluated.

This practice of evaluating expressions from left to right and stopping on the first true value is known as short-circuit evaluation. In particular, as seen in the Figure 8. The way to change the links in the site layout involves using an if-else branching structure inside of Embedded Ruby:.

A user is signed in if there is a current user in the session, i. There are four new links, two of which are stubbed out to be completed in Chapter 9 :. The signout link, meanwhile, uses the signout path defined in Listing 8. The full result appears in Listing 8. Note in particular the CSS ids and classes related to the Bootstrap dropdown menu. This uses the Sprockets library to include the Bootstrap JavaScript, which in turn is available thanks to the bootstrap-sass gem from Section 5.

With that change, a signed-in user now sees the new links and dropdown menu defined by Listing 8. At this point, you should verify that you can sign in, close the browser, and then still be signed in when you visit the sample application.

If you want, you can even inspect the browser cookies to see the result directly Figure 8. In principle, although we are now done with authentication, newly registered users might be confused, as they are not signed in by default.

Implementing this is the last bit of polish before letting users sign out. As discussed in Section 8. So far, the Sessions controller actions have followed the RESTful convention of using new for a signin page and create to complete the signin. The implementation is simple: we set the current user to nil and use the delete method on cookies to remove the remember token from the session Listing 8.

It is possible to do so, but experience shows that direct tests of cookie values are brittle and have a tendency to rely on implementation details that sometimes change from one Rails release to the next.

The result is breaking tests for application code that still works fine. By focusing on high-level functionality—verifying that users can sign in, stay signed in from page to page, and can sign out—we test the core application code without focusing on less important details. This section is optional and can be skipped without loss of continuity. Cucumber allows the definition of plain-text stories describing application behavior.

Many Rails programmers find Cucumber especially convenient when doing client work; since they can be read even by non-technical users, Cucumber tests can be shared with and can sometimes even be written by the client. Nevertheless, Cucumber does have a place in the Ruby testing toolkit, and I especially like its emphasis on high-level behavior over low-level implementation.

Note: A more recent version of the tutorial is available. To translate the Ruby on Rails Tutorial, simply fork this repository, clone it to your local machine, and get started translating it to your language of choice. If you want to work with other translators which I certainly encourage , add them as collaborators to the repository as needed.

At any time, you are free to deploy the result to a URL of your choice. Once it's up and ready for public consumption, send the URI to admin railstutorial. Since I often make minor fixes to the book, I recommend occasionally merging in changes from the master branch. If merging causes too many conflicts, you can omit this optional step. This is so that when you view the HTML files locally all the images load correctly. For a fully deployed version of the book, you may have to change the image paths from relative to absolute, such as.



0コメント

  • 1000 / 1000