Iteration C3: Using a Helper to Format the Price
Ruby provides a sprintf function that can be used to format prices. We could place logic that makes use of this function directly in the view. For example, we could say this:
| | <%= sprintf("$%0.02f", product.price) %> |
That would work, but it embeds knowledge of currency formatting into the view. If we display prices of products in several places and want to internationalize the application later, this would be a maintenance problem.
Instead, let’s use a helper method to format the price as a currency. Rails has an appropriate one built in, called number_to_currency.
Using our helper in the view is just a matter of invoking it as a regular method; in the index template, this ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access