Sha256: dbdb4389ab0d655b1db6b3f6ac4c9d68b5e4762cc7842cb4993d7f94b2ea1795

Contents?: true

Size: 805 Bytes

Versions: 1

Compression:

Stored size: 805 Bytes

Contents

require 'faraday'
require 'json'

module Wayback
  module Response
    class ParseAvailablity < Faraday::Response::Middleware

      def parse(body)
        case body
          when /^\{/
            obj = JSON.parse(body, :symbolize_names => true)[:archived_snapshots][:closest] rescue nil
            obj[:id] = obj[:timestamp] if obj && obj[:timestamp]
            obj
          else
            nil
        end
      end

      def on_complete(env)
        if respond_to?(:parse) && ((env[:response_headers] && env[:response_headers]['content-type']) || '').match(/^application\/javascript/i)
          env[:body] = parse(env[:body]) unless unparsable_status_codes.include?(env[:status])
        end
      end

      def unparsable_status_codes
        [204, 301, 302, 304]
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
wayback-0.3.1 lib/wayback/response/parse_availability.rb