So, a week or two ago I was modelling something with DataMapper and noticed that I needed some validation that went beyond the built-in validation macros. Now I could of just created my own validation macro as DataMapper makes this incredibly easy to do so, but I just needed something to get my specs to pass and go green.
Being a long time ActiveRecord user I immediately brought up the API documentation and went looking for the validates method. In AR, if you have something that doesn’t fit into one of the validation macros you simply override the validate method and push your errors onto the errors array. After a bit of poking around in the docs I couldn’t find anything that would fit my needs so I loaded up the DataMapper source code in TextMate and went searching. In order to make it easy for us AR old timers to switch over to DataMapper the authors were kind enough to create an AR impersonation module that wraps a few DataMapper methods in AR like methods. One of the is the save method and that’s where I noticed that DM called the valid? method before persisting the database session.
Now I have no idea if this is the official or the best way to do it but seeing this I realised that simply overriding the valid? method in my model, pushing my errors onto the errors array then calling super seemed to work fine for me. Now I’ve got to warn you that this relies on the internal workings of DataMapper and this could break in the future so use with caution. Of course you’re already writing specs/tests so this shouldn’t be too much of a problem:). By the way when adding errors if you have no attribute to bind the error to then passing in the context of :general is the recommended way of doing this.
June 2008 (1)
May 2008 (1)
April 2008 (2)
March 2008 (4)
February 2008 (1)
January 2008 (1)
December 2007 (2)
November 2007 (5)
October 2007 (3)
September 2007 (4)
August 2007 (1)
Online journal of Jonathan Conway a twenty something technologist, entrepreneur, husband, daddy of two, oh and lead architect at vzaar. Currently residing in London, UK.
You can find a little bit more about me here
My tumbler
vzaar
Brightbox Rails Hosting
My Caboose Facebook Profile
New Bamboo
Luke Redpath
Jamie Van Dyke
Peter Cooper
Ismael
Caroline
Monster Gym
Scala
Pat Allan
Cristi Balan

Comment on this article