Skip to content

Instantly share code, notes, and snippets.

@ozzyaaron
Created August 4, 2011 04:00
Show Gist options
  • Save ozzyaaron/1124475 to your computer and use it in GitHub Desktop.
Save ozzyaaron/1124475 to your computer and use it in GitHub Desktop.
def contact_details=(contacts)
return if contacts.nil?
contacts = contacts.values if contacts.kind_of? Hash
self.class.transaction do
phone_numbers.destroy_all
email_addresses.destroy_all
contacts.each do |contact|
value = contact[:value]
next if value.empty?
type = contact[:type]
display_name = contact[:type].split[0]
begin
case type
when /email/i
email_type = EmailType.find_by_display_name(display_name)
email_addresses.build(:address => value, :email_type => email_type)
when /phone|fax/i
phone_type = PhoneNumberType.find_by_display_name(display_name)
phone_numbers.build(:number => value, :phone_number_type => phone_type)
else
raise ArgumentError, "Unrecognized contact type #{type}, updating with value '#{value}'"
end
rescue ArgumentError => error
RAILS_DEFAULT_LOGGER.warn error.message
end
end
(email_addresses + phone_numbers).each do |contact|
begin
contact.save!
rescue ActiveRecord::RecordInvalid => error
if error.record.is_a?(EmailAddress)
errors.add :base, error.record.errors[:address]
elsif error.record.is_a?(PhoneNumber)
errors.add :base, error.record.errors[:number]
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment