Skip to content

Instantly share code, notes, and snippets.

@marcusmalmberg
Created November 23, 2012 00:01
Show Gist options
  • Save marcusmalmberg/4133383 to your computer and use it in GitHub Desktop.
Save marcusmalmberg/4133383 to your computer and use it in GitHub Desktop.
How to serve a vcard properly from amazon s3 in a rails app

This gist shows how to download a vcard with mime-type

It's easy to provide a simple link to download a vcard. The problem is that normal devices doesn't recognize the downloaded vcard and will most often just render them in the browser as plain text.

This gist is an example of how you can download the vcard with proper mime-type, which allows the device to recognize it as a vcard.

Prerequisites

This example assumes that you have a model Contact with a connected vcard. This example was built using a simple carrierwave uploader to upload the vcard to amazon s3.

# app/controllers/my_controller.rb
def download_vcard
respond_to do |format|
format.vcf do
contact = Contact.find_by_id(params[:id]) # Find the contact that's requested
return if contact.nil? # Make sure that the contact exists
tmp_file = open(contact.vcard.url) # This is needed to read the file from amazon (or any other remote url)
send_data tmp_file.read, :filename => contact.name.parameterize, :type => :vcf # Send the actual file with proper mime-type
end
end
end
# config/initializers/my_initializer.rb
Mime::Type.register 'text/x-vcard', :vcf # Add the mime-type for vcards
# app/views/my_controller/my_view.html.erb
<%= link_to("download vcard", download_vcard_path(contact.id, :format => 'vcf')) %>
# config/routes.rb
match 'vcard/:id', to: 'my_controller#download_vcard', :as => :download_vcard
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment