Cost/Wear: Part 2

Journal 07

My cost per wear (CpW) calculation is up and running! Plus I’ve added a number of other fields in, too. I’ve been working away and enjoying the coding side so much – I haven’t taken a moment to stop and write it out.

So, last time I focused on getting the cost to neatly display. Well. There’s been a lot more movement since then! I now have a whole bunch of things:

  • Number of wears (to divide the cost by and get the CpW value)
  • When the item was last worn (and a display showing how long ago that was)
  • A little ‘wear’ button that records the date and adds +1 wear to the count
  • Extra information fields such as where the item was made, the size, colour, RRP (and savings)…
  • Images & a placeholder image that takes the colour from the clothing item…

It’s been fun! It’s still quite basic, and not really styled at this point, but I’m focusing on getting the functionality right first and so far it’s working pretty well! I’m quite excited as I never really imagined this would be something I’d be able to build! (Again, massive thank you to the incredible Dennis for his ever-patient help!)

Let’s jump back a bit though, and finish writing about that core CpW feature.

Showing Wears

After adding wears to the database, making the usual migration and adding it as a param in the controller and going about to add it to the form (as a number input type) and show view… it was pretty straight forward to get the number of wears to come up!

<% if @article.wears %> 
	<p class="article__wears"><b><%= @article.wears %></b> wears</p>
<% end %>

Easy!

Calculating the CpW

Now with ‘cost’ and ‘number of wears’ at hand, calculating the cost per wear is really as simple as a little division. This can all be done in the Show view and requires a little extra logic as it does require a value for both cost and wears in order to work as well as ensuring that we don’t run into the divide by zero problem..

Adding this line at the start is great to ensure these conditions are met (or avoided):

<% if @article.cost && @article.wears && @article.wears != 0 %>

The && ensure that both cost and wears exist and will only continue if wears doesn’t equal 0.

After this, the maths can be added straight in:

Cost per wear: $<%= display_cost(@article.cost / @article.wears) %>

And that’s it! It’s up and calculates from those two numbers. 🙂