Things Well Made

Craftsmanship excellence and the design of beautiful things

Thing well made: detecting changes in Rails objects

March7

I’m a pretty big fan of Ruby on Rails and occasionally I come across some particularly well-made parts. Rails’ ability to track changes in objects in memory has been around well over a year but its staggering how much thought goes into what people might want.

How do I check the value of an object before it was changed?

Let’s say you want to keep track of the total amount a user has across all orders. Rails has built-in not only a convenient place to update the value, but it has the previous value so you can find out the difference.

So nice!

In the example below,

  • there is a field in the order table called ‘order_total’.
  • order_total_change is Rails-generated array returning e.g. [20.53, 21.52] if say, the order_total had gone up by 1.99.
  • order_total_changed? is also Rails-autogenerated.
class Order
...
before_update :update_total_user_spend
...
def update_total_user_spend
  if order_total_changed?
    previous_value, new_value = self.order_total_change
    self.user.total_spend += new_value - previous_value
    self.user.save
  end
end

Rock on!

(yes and I do need to adjust this blog template so it has a little more room for CONTENT :)

Bruce on Rails

Email will not be published

Website example

Your Comment:

I’ve always appreciated things that have had love, care and attention put into them. Where its obvious that the thing that was created was created for reasons above purely commercial gain.

Don McGlashan says it best in ‘Thing Well Made’ by the Mutton Birds:

To make a thing like that you’d need to know what you were about.
You’d have to know where you were going and go there in a straight line.
And everything else you’d have to shut right out.
Can you see the man who made that?
Can you see him putting it down and standing back?
Can you see the moment when he said “That’s it. That’s perfect.”?
At a time like that you wouldn’t care about your job,
Or your mortgage, or the fight you had with your wife.
‘Cause when a man holds a thing well made,
There’s connection,
There’s completeness when a man holds a thing well made.

Watch live recording of A Thing Well Made by the Mutton Birds

This site is dedicated to this song and to all those people in the world who create Things Well Made.



 

You need to log in to vote

The blog owner requires users to be logged in to be able to vote for this post.

Alternatively, if you do not have an account yet you can create one here.

Powered by Vote It Up