Sinatra doesn't like £ signs

Over the last few weeks, since launching this new version of the site, there have been several encoding errors. The error message given was "incompatible character encodings: US-ASCII and UTF-8". They seemed to be on all pages where there were unusual characters. For example the, “, ” and ? characters were all causing issues.

After Googling the issue it was found that Ruby isn't the most friendly language when it comes to string encoding. One suggestion found was to use a # encoding: UTF-8 comment at the top of each file, this did not work. Another suggestion was to use the force_encoding("UTF-8") method to make sure the string is UTF-8, this did not work either.

On further investigation it was found that all the strings being output were already UTF-8, but the issue was still there.

Finally one Stackoverflow comment saved the day. "This is an issue in Tilt, the templating system that Sinatra uses... The problem is basically down to how Tilt reads template files from the disk..."

The solution was to use File.read to load the views. Previously the blog post views were bring loaded using the syntax erb :blog_post, this was changes to:

erb File.read './views/blog_post.erb'`.

After changing this on all views loaded, the issues have gone away.

Published on: 05 December 2012
By
Tags: ruby, sinatra,

Simple SEO PDF guide

Get our latest PDF guide, Simple SEO.

Twitter