Simple App V (TDD - Dynamic Pages, Embedded Ruby) 2020
The technique involves using Embedded Ruby in our views. Since the Home, Help, and About page titles have a variable component, we'll use a special Rails function called provide to set a different title on each page. We can see how this works by replacing the literal title "Home" in the home.html.erb view with the following code:
app/views/static_pages/home.html.erb:
<% provide(:title, 'Home') %> <!DOCTYPE html> <html> <head> <title>Ruby on Rails Tutorial Simple App | <%= yield(:title) %></title> </head> <body> <h1>Simple App</h1> <p> This is the home page for the <a href="http://www.bogotobogo.com/RubyOnRails/RubyOnRails.php">Ruby on Rails Tutorial</a> simple application. </p> </body> </html>
The code is an example of Embedded Ruby (ERb) which is the primary template system for including dynamic content in web pages.
The code:
<% provide(:title, 'Home') %>
indicates using <% ... %> that Rails should call the provide function and associate the string 'Home' with the label :title. Then, in the title, we use the closely related notation <%= ... %> to insert the title into the template using Ruby's yield function:
<title>Ruby on Rails Tutorial Simple App | <%= yield(:title) %></title>
(The distinction between the two types of embedded Ruby is that <% ... %> executes the code inside, while <%= ... %> executes it and inserts the result into the template.) The resulting page is exactly the same as before, only now the variable part of the title is generated dynamically by ERb.
We can verify that all this works by running the tests and see that they still pass:
$ bundle exec rspec spec/requests/static_pages_spec.rb ...... Finished in 0.51964 seconds 6 examples, 0 failures Randomized with seed 925
Same to Help and About:
<% provide(:title, 'Help') %> <!DOCTYPE html> <html> <head> <title>Ruby on Rails Tutorial Simple App | <%= yield(:title) %></title> </head> <body> <h1>Help</h1> <p> Get help on the Ruby on Rails Tutorial at the <a href="http://www.bogotobogo.com/RubyOnRails/RubyOnRails.php/Help">Rails Tutorial help page</a>. </p> </body> </html>
<% provide(:title, 'About Us') %> <!DOCTYPE html> <html> <head> <title>Ruby on Rails Tutorial Simple App | <%= yield(:title) %></title> </head> <body> <h1>About Us</h1> <p> The <a href="http://www.bogotobogo.com/RubyOnRails/RubyOnRails.php">Ruby on Rails Tutorial</a> is a project to make a book and screencasts to teach web development </p> </body> </html>
We can see that they still pass the tests:
$ bundle exec rspec spec/requests/static_pages_spec.rb ...... Finished in 0.53112 seconds 6 examples, 0 failures Randomized with seed 52077
Ph.D. / Golden Gate Ave, San Francisco / Seoul National Univ / Carnegie Mellon / UC Berkeley / DevOps / Deep Learning / Visualization