Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Merge pull request #40 from grosser/iso-dates

add middleware to parse iso dates
  • Loading branch information...
commit 7cad490094b87b77a061076d2ed0343648b5280f 2 parents 8fccad6 + 27c4e1c
@sferik sferik authored
View
39 lib/faraday_middleware/response/parse_dates.rb
@@ -0,0 +1,39 @@
+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
View
42 spec/parse_dates_spec.rb
@@ -0,0 +1,42 @@
+require 'helper'
+require 'faraday_middleware/response/parse_dates'
+require 'json'
+
+describe FaradayMiddleware::ParseDates, :type => :response do
+ let(:parsed){
+ if RUBY_VERSION > "1.9"
+ "2012-02-01 13:14:15 UTC"
+ else
+ "Wed Feb 01 13:14:15 UTC 2012"
+ end
+ }
+
+ it "should parse dates" do
+ process({"x" => "2012-02-01T13:14:15Z"}).body["x"].to_s.should == parsed
+ end
+
+ it "should parse nested dates in hash" do
+ process({"x" => {"y" => "2012-02-01T13:14:15Z"}}).body["x"]["y"].to_s.should == parsed
+ end
+
+ it "should parse nested dates in arrays" do
+ process({"x" => [{"y" =>"2012-02-01T13:14:15Z"}]}).body["x"][0]["y"].to_s.should == parsed
+ end
+
+ it "should not blow up on empty body" do
+ process(nil).body.should == nil
+ end
+
+ it "should leave arrays with ids alone" do
+ process({"x" => [1,2,3]}).body.should == {"x" => [1,2,3]}
+ end
+
+ it "should not parse date-like things" do
+ process({"x" => "2012-02-01T13:14:15Z bla"}).body["x"].to_s.should ==
+ "2012-02-01T13:14:15Z bla"
+ process({"x" => "12012-02-01T13:14:15Z"}).body["x"].to_s.should ==
+ "12012-02-01T13:14:15Z"
+ process({"x" => "2012-02-01T13:14:15Z\nfoo"}).body["x"].to_s.should ==
+ "2012-02-01T13:14:15Z\nfoo"
+ end
+end
Please sign in to comment.
Something went wrong with that request. Please try again.