Sha256: c6e5f178b611c165f99cd50d4c13a0cf6526ff82d9716fda441867a73e8b9637

Contents?: true

Size: 834 Bytes

Versions: 4

Compression:

Stored size: 834 Bytes

Contents

require "time"
require "faraday"

module FaradayMiddleware
  # Parse dates from response body
  class ParseDates < ::Faraday::Response::Middleware
    ISO_DATE_FORMAT = /\A\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z\Z/m

    def initialize(app, options = {})
      @regexp = options[:match] || ISO_DATE_FORMAT
      super(app)
    end

    def call(env)
      response = @app.call(env)
      parse_dates! response.env[:body]
      response
    end

    private

    def parse_dates!(value)
      case value
      when Hash
        value.each do |key, element|
          value[key] = parse_dates!(element)
        end
      when Array
        value.each_with_index do |element, index|
          value[index] = parse_dates!(element)
        end
      when @regexp
        Time.parse(value)
      else
        value
      end
    end
  end
end

Version data entries

4 entries across 4 versions & 2 rubygems

Version Path
agiley-faraday_middleware-0.9.1 lib/faraday_middleware/response/parse_dates.rb
agiley-faraday_middleware-0.9.0 lib/faraday_middleware/response/parse_dates.rb
faraday_middleware-0.9.0 lib/faraday_middleware/response/parse_dates.rb
faraday_middleware-0.8.8 lib/faraday_middleware/response/parse_dates.rb