Skip to content

Instantly share code, notes, and snippets.

@skaes
Created August 9, 2010 10:56
Show Gist options
  • Save skaes/515276 to your computer and use it in GitHub Desktop.
Save skaes/515276 to your computer and use it in GitHub Desktop.
# try to fix broken string encodings. most of the time the string is latin-1 encoded
if RUBY_VERSION >= "1.9"
def safe_h(s)
h(s)
rescue ArgumentError
raise unless $!.to_s == "invalid byte sequence in UTF-8"
logger.debug "#{$!} during html escaping".upcase
begin
h(s.force_encoding('ISO-8859-1').encode('UTF-8', :undef => :replace))
rescue ArgumentError
h(s.force_encoding('ASCII-8BIT').encode('UTF-8', :undef => :replace))
end
end
else
def safe_h(s)
h(s)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment