Sha256: e9ee9041d912fc52ce938cb0df37364cae2e9a321642e3f6511b79b5f9ffbabe

Contents?: true

Size: 842 Bytes

Versions: 3

Compression:

Stored size: 842 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}(\.\d+)?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

3 entries across 3 versions & 1 rubygems

Version Path
faraday_middleware-0.10.0 lib/faraday_middleware/response/parse_dates.rb
faraday_middleware-0.9.2 lib/faraday_middleware/response/parse_dates.rb
faraday_middleware-0.9.1 lib/faraday_middleware/response/parse_dates.rb