Wednesday, June 01, 2011

ActiveModel Object With Multi-Part Attribute/Date Support

Simple Ruby ActiveModel class that works with View and Form helpers in Rails 3. Appears to handle dates properly. Let me know if any problems arise:


class CreditCard
include ActiveModel::Validations
include ActiveModel::Conversion
extend ActiveModel::Naming

attr_accessor :name
attr_accessor :number
attr_accessor :expiration_date
attr_accessor :code

validates_presence_of [ :name, :number, :expiration_date, :validation_code ]
validates_format_of :number, :with => /^\d+$/, :if => Proc.new {|o| !o.card_number.blank? && !o.errors[:card_number] }
validates_format_of :code, :with => /^\d+$/, :if => Proc.new {|o| !o.code.blank? && !o.errors[:code] }

def initialize( attrs = {} )
if !attrs.nil? then
dattrs = {}
attrs.each do |n, v|
if n.match( /^(.+)\(.+\)$/ ) then
an = Regexp.last_match[1]
dattrs[an] = [] if dattrs[an].nil?
dattrs[an] << { :n => n, :v => v }
else
send( "#{n}=", v)
end
end
dattrs.each do |k, v|
vs = v.sort_by{|hv| hv[:n] }.collect{|hv| hv[:v] }
p1 = vs[0]
p2 = ( vs[1].size() > 0 ? ( vs[1].size() == 1 ? "0#{vs[1]}" : vs[1] ) : "01" )
p3 = ( vs[2].size() > 0 ? ( vs[2].size() == 1 ? "0#{vs[2]}" : vs[2] ) : "01" )
dv = [ p1, p2, p3 ].join( "-" )
begin send( "#{k}=", Date.parse( dv ) ); rescue; end
end
end
end

def persisted?
false
end

end

0 Comments:

Post a Comment

<< Home