Showing posts with label ascii. Show all posts
Showing posts with label ascii. Show all posts

Thursday, 5 June 2014

Writing files in a specific encoding in Ruby

Recently, I was trying to create PDF files of barcodes. I was using barby gem for generating barcodes. When I tried to write the generated PDF, I found that the PDF string was in ASCII-8BIT encoding while my console was in UTF-8 which was causing Ruby to attempt writing in UTF-8 encoding causing errors. So, to write to the file in ASCII-8BIT, I had to specify that while opening the file. I achieved that using the following and I could write to the file correctly.

f = File.open("test.pdf", "w:ASCII-8BIT")
f.write the_pdf_string
f.close

Friday, 16 November 2012

UTF-8 encoded Rails Console in linux

Although, initially while working on Rails project, we do not pay much attention to the character encoding, soon it bites us bad. When we try to play with a string containing Unicode characters in an ASCII encoded Rails console, it complains about it and we are stuck.

It is quite easy to get a UTF-8 encoded Rails console. All we need to do is properly set the LANG environment variable of the terminal first.

export LANG=en_US.UTF-8

Rails picks up this variable and sets its encoding. So, when we fire up Rails console now and enter the following command, it shows that we have UTF-8 encoded console.

puts __ENCODING__

Now, we can easily play with UTF-8 strings.