firstruby

Master ruby with us

vCard Exporting to *.vcf file through RubyOnRails

Posted by firstruby on December 10, 2007

To Export vCard of Contacts for offline access, install vpim gem,

gem install vpim

In Controller, code to export contact to vCard (export to *.vcf file) should be as follows

require 'vpim/vcard'
class VcardController < ApplicationController
def get_contact
contact = Address.find(params[:id])
company = OfficeAddress.find(contact.office_address_id)

card = Vpim::Vcard::Maker.make2 do |maker|

maker.add_name do |name|
name.given = contact.firstname + ‘ ‘ + contact.lastname
end

maker.add_addr do |addr|
addr.location = ‘home’
addr.street = contact.street
addr.locality = contact.area
addr.region = contact.state
addr.postalcode = contact.pin
addr.country = contact.country
end

maker.add_addr do |addr|
addr.location = ‘work’
addr.street = company.street
addr.locality = company.area
addr.region = company.state
addr.postalcode = company.pin
addr.country = company.country
end

if !contact.ph_resi.empty?
maker.add_tel(contact.ph_resi) do |tel|
tel.location = ‘home’
tel.preferred = true
end
end

if !contact.ph_office.empty?
phone = contact.ph_office
maker.add_tel(phone) do |tel|
tel.location = ‘work’
tel.preferred = true
end
end

if !contact.fax.empty?
maker.add_tel(contact.fax) do |tel|
tel.location = ‘work’
tel.capability = ‘fax’
end
end

if !contact.mobile.empty?
maker.add_tel(contact.mobile) do |tel|
tel.location = ‘home’
tel.capability = ‘mobile’
end
end

maker.add_email(contact.email) do |e|
e.location = ‘work’
end

end

send_data card.to_s,
:filename => “contact.vcf”
end
end

Advertisements

2 Responses to “vCard Exporting to *.vcf file through RubyOnRails”

  1. Just in case someone was looking for this. You can import vcards by using the following snippet. This assumes the user is uploading the vcard file.

    @cards = Vpim::Vcard.decode(params[:import_file].read)

  2. Good post. If someone ever needs to add a charset to an exportet vpim I explain how to it here: http://blog.andischacke.com/2008/10/add-character-set-to-vpims-vcard-export.html

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: