I recently had to do some work populating a model from complex virtual
attributes. However, I also wanted to be able to leverage the
validations framework to be able to add descriptions of errors that
existed in virtual attribute values. I'm wondering how to avoid
duplication between the code that transforms the virtual attributes
into real attributes, and the code that does the validation.
This is probably best demonstrated with a simplified example.
Before I start, it's worth noting that this situation is a little
unusual in that it uses a model that isn't actually created by the
user via a form. Instead, I have a Ruby process that monitors a POP3
server and, whenever a new email is received, parses the mail to
determine the sender from the email address, and saves it to the
database via a 'Message' model. If any errors occur saving the
message, it writes the errors to the log. I won't go into the details
of checking the POP3 server, but suffice to say that I'd like the code
that actually processes each email to look something like this:
message = Message.new(:mail => mail)
// Write out the message validation errors to the log.
To support this, the Message model includes a 'mail' virtual
attribute. Assuming that this attribute is a TMail::Mail object, the
Message model looks something like this:
class Message < ActiveRecord::Base
@mail = mail
self.sender = Sender.find_by_email_address(mail.from_addrs) if
mail.from_addrs.size == 1
from_addresses = @mail.from_addrs
if from_addresses.size == 1
errors.add("'From' address", "is not a known sender ") unless
errors.add("'From' addresses", "expected to contain one email
My concern is the duplicated logic for checking whether there's just
one email address. It mightn't look too bad now, but rapidly becomes a
pain when many other parts of the email have to be parsed and
validated (as is the case in real life). It's also worth keeping in
mind that I have to double up my testing too.
I thought about just raising an exception if there were any problems
when setting the virtual attribute. However, this brought it's own
complexities - to do it properly I have to define a custom exception
class, and get the caller to check if it has been raised.
I also thought about adding the errors in the virtual attribute setter
instead of the validate() method, but I've never seen this done before
and am not sure what side-effects it might have.