Ruby On Rails Lesson
Changing the Layout Links
We come finally to a practical application of all our signin/out work: We’ll change the layout links based on signin status. In particular, as seen in the Figure 8.3 mockup, we’ll arrange for the links to change when users sign in or sign out, and we’ll also add links for listing all users and user settings (to be completed in Chapter 9) and one for the current user’s profile page. In doing so, we’ll get the tests in Listing 8.6 to pass, which means our test suite will be green for the first time since the beginning of the chapter. The way to change the links in the site layout involves using an if-else branching structure inside of Embedded Ruby:
This kind of code requires the existence of a signed_in? boolean, which we’ll now define. A user is signed in if there is a current user in the session, i.e., if current_user is non-nil. This requires the use of the ‘‘not’’ operator, written using an exclamation point ! and usually read as ‘‘bang.’’ In the present context, a user is signed in if current_user is not nil, as shown in Listing 8.23.
With the signed_in? method in hand, we’re ready to finish the layout links. 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.2:
(Notice that the signout link passes a hash argument indicating that it should submit with an HTTP DELETE request.8) Finally, we’ll add a profile link as follows:
Here we could write
but Rails allows us to link directly to the user, in this context automatically converting current_user into user_path(current_user).
In the process of putting the new links into the layout, we’ll take advantage of Bootstrap’s ability to make dropdown menus, which you can read more about on the Bootstrap components page. The full result appears in Listing 8.24. Note in particular the CSS ids and classes related to the Bootstrap dropdown menu.