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​)​ ​%​>

This 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 is the code we start with:

 <​%=​ product​.​price ​%​>

We can change it to the following:

 <div class=​"price"​>
 <%=​ number_to_currency(product.​price​) ​%>
 </div>

When we refresh, we see a nicely formatted price, as in the following screenshot.

images/e_2_prices_fixed.png

Although it looks nice enough, we’re starting to get a nagging feeling that we really should be running and writing tests for all this new functionality, particularly after our experience of adding logic to our model.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.14.253.221