Skip to content

Instantly share code, notes, and snippets.

@Malet
Last active December 31, 2015 05:49
Show Gist options
  • Save Malet/7942995 to your computer and use it in GitHub Desktop.
Save Malet/7942995 to your computer and use it in GitHub Desktop.
Prevent invalid UTF-8 byte sequences for Ruby 2.0 / 2.1 (1.9 untested)
class String
REPLACE_INVALID_WITH = '�'
def to_utf8
self.encode('utf-8', invalid: :replace, undef: :replace, replace: REPLACE_INVALID_WITH).
chars.map{ |i| i.valid_encoding? ? i : REPLACE_INVALID_WITH }.join
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment