Incompatible character encodings - Rails patch for Ruby 1.9.1 | 08. April 2010 um 14:50 Uhr / Programming

Eingestellt am 08. April 2010 um 14:50 Uhr » Programming

For quite some time I had a problem with Rails under Ruby 1.9.1. Sometimes it just throwed this error and I didn't know what to do:

incompatible character encodings: UTF-8 and ASCII-8BIT

But I think now I found a solution, at least for my case. It was always the content around the TextHelper method markdown. After some trying I found out that if I call markdown(text).force_encoding("utf-8") the problem would go away.

So that was great, but I use markdown all over the place. I also didn't want to patch the Rails code directly, so I tried to write my first "Monkey Path" for Rails.

And here it is, it's unobtrusive, not aware of anything and will work in the future too, even if they change the argument list or behaviour of the markdown method. And it doesn't break anything in 1.8.x either.

# config/initializers/monkeypatch_markdown.rb
module ActionView
  module Helpers
    module TextHelper
      def markdown_with_encoding_utf8(*args)
        result = markdown_without_encoding_utf8(*args)
        result.encoding("utf-8") if result.respond_to?(:encoding)
      end
      alias_method_chain :markdown, :encoding_utf8
    end
  end
end

Kommentare

Die Kommentare sind für diesen Eintrag geschlossen.