Ruby: Convert Strings from UTF-8 to LATIN1 (ISO 8859-1) with Iconv
Posted: April 30th, 2009 | Author: vid | Filed under: Development | Tags: ruby | No Comments »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
require 'iconv'"
Then convert the VCard that was created with UTF-8 encoded data to LATIN1 and send it to the user’s browser
# 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"
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.
Leave a Reply