Skip to content

Instantly share code, notes, and snippets.

@n-at-han-k
Created March 30, 2025 10:16
Show Gist options
  • Select an option

  • Save n-at-han-k/e044953609bd3aacbe8e319994a00804 to your computer and use it in GitHub Desktop.

Select an option

Save n-at-han-k/e044953609bd3aacbe8e319994a00804 to your computer and use it in GitHub Desktop.
Extract and convert data from VCF Vcards to CSV in Ruby
#!/usr/bin/env ruby
#require 'pp'
require 'vpim/vcard'
require 'csv'
COLUMN_ORDER = %w[
given_name
landline
mobile
email
address
]
cards = Vpim::Vcard.decode(File.open('vcard.vcf'))
class VcardExport
def initialize(vcard)
@card = vcard
end
def to_hash
{
name: name,
email: email,
address: address,
phone: phone,
}
end
def to_array
[
name, # given_name
'', # landline
phone, # mobile
email, # email
address, # address
]
end
def name
if @card.name.fullname.empty?
@card.org.first
else
@card.name.fullname
end
end
def email = @card.email.to_s
def address
[
@card.address.pobox,
@card.address.street,
@card.address.locality,
@card.address.region,
@card.address.postalcode,
].select{|a| not a.empty?}.join(', ')
end
def phone
@card.telephone
end
end
cards_with_full_name = []
cards_with_out_name = []
cards.each do |card|
if card.name.fullname.empty?
cards_with_out_name << VcardExport.new(card)
else
cards_with_full_name << VcardExport.new(card)
end
end
#cards_with_full_name.each do |card|
# puts card.to_hash
#end
#
#cards_with_out_name.each do |card|
# puts card.to_hash
#end
all_cards = cards_with_full_name.concat(cards_with_out_name)
CSV.open("contacts.csv", "w") do |csv|
csv << COLUMN_ORDER
all_cards.each do |card|
csv << card.to_array
end
end
@n-at-han-k
Copy link
Author

Very specific usage here, but I think would be a good starting point for anyone.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment