2.8 Embedded Ruby Tags
What can we do with this new system? Add the following to our embedded Ruby file:
<!-- app/views/game_templates/user_rock.html.erb -->
<h2>We played rock!</h2>
<h2>
They played <%= %>!
</h2>
{: mark_lines=“5-7”}
We created a new tag that looks like HTML, but contains a doorway to Ruby: <%= %>
. We can write any Ruby we want in that embedded Ruby tag. This is what makes the whole effort of RCAV worthwhile!
For instance, we can write:
<!-- app/views/game_templates/user_rock.html.erb -->
<h2>We played rock!</h2>
<h2>
They played <%= 6 * 7 %>!
</h2>
{: mark_lines=“6”}
And we will see the result of this computation when we refresh /rock. (Did you save the changes in the file before refreshing the browser?) But, if we right-click and “View page source” in the browser, we won’t see the Ruby code. We only see the result 42
.
The browser only understands HTML and has no idea of the code that allows us to make the web application dynamic. Rails is processing all of the embedded Ruby tags and injecting them in the document before it sends the plain HTML file to the browser.
We could also do something like:
<!-- app/views/game_templates/user_rock.html.erb -->
<h2>We played rock!</h2>
<% comp_move = ["rock", "paper", "scissors"].sample %>
<h2>
They played <%= 6 * 7 %>!
</h2>
{: mark_lines=“5”}
Here, we used a slightly different embedded Ruby tag: <% %>
. We left off the =
sign, which means the output of this Ruby code will be hidden in the rendered HTML. But, the variable comp_move
(the result of randomly sampling an array of three possible String
values) is still available and we can render that by changing the file again:
<!-- app/views/game_templates/user_rock.html.erb -->
<h2>We played rock!</h2>
<% comp_move = ["rock", "paper", "scissors"].sample %>
<h2>
They played <%= comp_move %>!
</h2>
{: mark_lines=“8”}
Our calculated variable comp_move
is now rendered in the final HTML output, because it is in a <%= %>
tag, with the =
sign. And we will see the result of this computation when we refresh /rock. Again, “View page source” here and you won’t see any sign of the comp_move
variable computation from the <% %>
tag.
Alright, we are now finally building dynamic web applications. We are able to render a template, we are able to write some HTML, and we are able to use embedded Ruby tags: <% %>
for hidden content, and <%= %>
for rendered content.