Class: LinkPreview::ForceUTF8Body

Inherits:
Faraday::Middleware
  • Object
show all
Defined in:
lib/link_preview/http_client.rb

Instance Method Summary collapse

Instance Method Details

#call(env) ⇒ Object



57
58
59
60
61
# File 'lib/link_preview/http_client.rb', line 57

def call(env)
  @app.call(env).on_complete do |response_env|
    force_utf8_body!(response_env)
  end
end

#force_utf8_body!(env) ⇒ Object



46
47
48
49
50
51
52
53
54
55
# File 'lib/link_preview/http_client.rb', line 46

def force_utf8_body!(env)
  return if env[:body].encoding == Encoding::UTF_8 && env[:body].valid_encoding?
  return unless env[:response_headers][:content_type] =~ /text/
  env[:body].encode!('UTF-8', 'binary', invalid: :replace, undef: :replace, replace: '')
  return if env[:body].valid_encoding?
  # cleanse untrusted invalid bytes with a double transcode as suggested here:
  # http://stackoverflow.com/questions/2982677/ruby-1-9-invalid-byte-sequence-in-utf-8
  env[:body].encode!('UTF-16', 'binary', invalid: :replace, undef: :replace, replace: '')
  env[:body].encode!('UTF-8', 'binary', invalid: :replace, undef: :replace, replace: '')
end