Re: How to use validation with aggregation (composed_of)?

Mark Reginald James
2005-12-17T04:24:07Z

Simon Harris wrote:

> ActiveRecord supports composed_of for value objects which is  fantastic
> but one thing that it doesn''t seem to support (or at least  I am
unable
> to find any documentation for) validation of the value  objects.

Here''s an attempt at a solution.  Any better way?

class Message < ActiveRecord::Base
   composed_of :sender, :class_name => ''EmailAddress'',
               :mapping => [[:sender_name], [:sender_address]]

   composed_of :recipient, :class_name => ''EmailAddress'',
               :mapping => [[:recipient_name], [:recipient_address]]

   def validate
     [''sender'', ''recipient''].each do |attr|
       obj = self.send(attr)
       [''name'', ''address''].each do |field|
         msg = obj.send("valid_#{field}?")
         # choose one of the following
         errors.add_to_base( "#{attr}''s #{field} #{msg}" )
unless msg.blank?
         errors.add( "#{attr}_#{field}", msg ) unless msg.blank?
       end
     end
     super
   end
end

class EmailAddress
   attr_reader :name, :address

   def initialize( name, address )
     @name, @address = name, address
   end

   def valid_address?
     @valid_address ||       check_valid?( @address ) ? '''' :
''is not a valid email address''
   end

   def valid_name?
     @valid_name ||       if @name.blank?
         ''cannot be blank''
       elsif @name =~ /[A-Za-Z][A-Za-z -]*/
         ''''
       else
         ''contains invalid characters''
       end
   end
end

--
We develop, watch us RoR, in numbers too big to ignore.