Ruby: Convert Strings from UTF-8 to LATIN1 (ISO 8859-1) with Iconv

I used VPIM to create VCards from employees in my database which stores the employee’s data UTF-8 encoded. Then I wanted to give the user the possibility to download them. And of course half of the employees’ names were corrupted because I didn’t convert them to LATIN1 (ISO 8859-1). so here’s what i came up with:

First include Iconv in your .rb file

1
require 'iconv'"

Then convert the VCard that was created with UTF-8 encoded data to LATIN1 and send it to the user’s browser

1
2
3
4
5
6
7
8
# create vcard
card = create_vcard()

# create LATIN1 encoded string from card
encoded_card = Iconv.iconv("LATIN1", "UTF-8", card.to_s).join

# and send it to the browser
send_data  encoded_card, :type => "text/vcf; charset=iso-8859-1", :filename => "contact.vcf"

That’s basicly how to convert strings with Iconv.

Tags:

Leave a Reply