Using a Helper to Format the Price
Learn to use helper functions in Ruby.
We'll cover the following
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) %>
While this would work, it embeds knowledge of currency formatting into the view. If we display the 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 is the code we start with:
<%= product.price %>
Get hands-on with 1400+ tech skills courses.