Sha256: 7ac5fcfafd22a9c1114e7d389025208e69666487b2d7e92ec95a77de42938838

Contents?: true

Size: 796 Bytes

Versions: 1

Compression:

Stored size: 796 Bytes

Contents

# frozen_string_literal: true

module LinkThumbnailer
  class Response
    def initialize(response)
      @response = response
    end

    def charset
      @charset ||= extract_charset
    end

    def body
      @body ||= extract_body
    end

    private

    def extract_charset
      content_type = @response['Content-Type'] || ''
      m = content_type.match(/charset=(\w+)/)
      (m && m[1]) || ''
    end

    def extract_body
      should_convert_body_to_utf8? ? convert_encoding_to_utf8(@response.body, charset) : @response.body
    end

    def should_convert_body_to_utf8?
      charset != '' && charset != 'utf-8'
    end

    def convert_encoding_to_utf8(body, from)
      Encoding::Converter.new(from, 'utf-8').convert(body)
    rescue EncodingError
      body
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
link_thumbnailer-3.3.2 lib/link_thumbnailer/response.rb