gitlabhq/lib/gitlab/encode.rb

42 lines
1.2 KiB
Ruby
Raw Normal View History

# Patch Strings to enable detect_encoding! on views
require 'charlock_holmes/string'
module Gitlab
2012-05-29 10:16:59 +02:00
module Encode
2012-04-11 22:03:56 +02:00
extend self
def utf8 message
2012-05-29 10:16:59 +02:00
# return nil if message is nil
return nil unless message
2012-05-30 07:40:47 +02:00
message.force_encoding("utf-8")
2012-05-30 05:44:36 +02:00
# return message if message type is binary
detect = CharlockHolmes::EncodingDetector.detect(message)
return message if detect[:type] == :binary
2012-05-29 10:16:59 +02:00
# if message is utf-8 encoding, just return it
return message if message.valid_encoding?
2012-05-30 05:44:36 +02:00
# if message is not utf-8 encoding, convert it
if detect[:encoding]
2012-05-29 10:16:59 +02:00
message.force_encoding(detect[:encoding])
message.encode!("utf-8", detect[:encoding], undef: :replace, replace: "", invalid: :replace)
2012-05-29 10:16:59 +02:00
end
2012-05-30 05:44:36 +02:00
# ensure message encoding is utf8
2012-05-29 10:16:59 +02:00
message.valid_encoding? ? message : raise
# Prevent app from crash cause of encoding errors
rescue
2012-06-17 21:00:13 +02:00
encoding = detect ? detect[:encoding] : "unknown"
"--broken encoding: #{encoding}"
2012-04-11 22:03:56 +02:00
end
def detect_encoding message
return nil unless message
hash = CharlockHolmes::EncodingDetector.detect(message) rescue {}
return hash[:encoding] ? hash[:encoding] : nil
2012-04-11 22:03:56 +02:00
end
end
end