Make Dynamic Pages
In order to get dynamic pages, I need to embed some ruby code into the *.rhtml in views.
First, I introduce some symbols in *.rhtml.
<%= %> : content between <%= %> is interpreted as ruby code and executed. The result of that execution is converted into a string, and that value is substituted into the file in place of the <%= %> sequence.
<% %> : mostly the same as <%= %>, except the result did not display—never converted into a string and never substituted into the file.
<%= -%> : tell rails to remove any new line that follows from the output.
h( ) : prevent the special characters from grabling the browser display—they’ll escape as html entities.
Now, we create a page to display the current time when you refresh the page.
In order to accord with the spirit of MVC, first we save the current time in a variable in the controller’s method, then we use the variable to display the current time in views.
class SayController > ApplicationController
@time = Time.now
<h1>Hello from Rails!</h1>
It is now <%= @time %>
Save this file, you’ll see the current time when you refresh the page.
Our story illustrates convention over configuration, one of the fundamental parts of the philosophy of Rails.
Link Pages Together
There are two way to link pages together.
<a href = “/say/goodbye”>Goodbye</a>
Rails use a convention to parse the URL into a target controller and an action within that controller. Here say is controller, goodbye is the action in say.
Flaw: the hyperlink path is relative, if we move the application to a different place on the web server, the URL would no longer be valid.
:action : Ruby symbol, you can think of the colon as meaning the thing named…, so :action means the thing named action, the => “goodbye” associate the string goodbye with the name action.