From 56f27d2a18e031bd555e9701fb4a8b2afd2e72b2 Mon Sep 17 00:00:00 2001 From: Brian Stien Date: Tue, 27 Feb 2018 16:54:00 -0700 Subject: [PATCH] Handle invalid DateTime attributes gracefully The Date typecaster will gracefully handle invalid dates, but DateTime does not. This changes the behavior of DateTime types to match the behavior of Date types. --- lib/active_remote/typecasting/date_time_typecaster.rb | 1 + spec/lib/active_remote/typecasting_spec.rb | 7 +++++++ 2 files changed, 8 insertions(+) diff --git a/lib/active_remote/typecasting/date_time_typecaster.rb b/lib/active_remote/typecasting/date_time_typecaster.rb index 91b5369..cf01d71 100644 --- a/lib/active_remote/typecasting/date_time_typecaster.rb +++ b/lib/active_remote/typecasting/date_time_typecaster.rb @@ -3,6 +3,7 @@ module Typecasting class DateTimeTypecaster def self.call(value) value.to_datetime if value.respond_to?(:to_datetime) + rescue NoMethodError, ArgumentError end end end diff --git a/spec/lib/active_remote/typecasting_spec.rb b/spec/lib/active_remote/typecasting_spec.rb index d672a3d..dce5798 100644 --- a/spec/lib/active_remote/typecasting_spec.rb +++ b/spec/lib/active_remote/typecasting_spec.rb @@ -14,6 +14,13 @@ record = test_class.new(:birthday => "2016-01-01") expect(record.birthday).to eq(DateTime.parse("2016-01-01")) end + + context "invalid date" do + it "sets attribute to nil" do + record = test_class.new(:birthday => "23451234") + expect(record.birthday).to be_nil + end + end end describe "float" do