Skip to content
This repository
Browse code

Better error message for String#to_date

I did this because to_date gives a very unhelpful error message if you
do not pass in a correct date. In the process I think this cleans up the
 code nicely and even better it tends to be slightly faster than the
 current implementation.

Benchmark
https://gist.github.com/4440875
  • Loading branch information...
commit ebd27d5714e20e6301a52989ae3c9e73f55ce29d 1 parent fba6a6a
Kelly Stannard authored
8  activesupport/CHANGELOG.md
Source Rendered
... ...
@@ -1,5 +1,13 @@
1 1
 ## Rails 4.0.0 (unreleased) ##
2 2
 
  3
+*   Change String#to_date to use Date.parse. This gives more consistant error
  4
+    messages and allows the use of partial dates.
  5
+
  6
+        "gibberish".to_date => Argument Error: invalid date
  7
+        "3rd Feb".to_date => Sun, 03 Feb 2013
  8
+
  9
+    *Kelly Stannard*
  10
+
3 11
 *   It's now possible to compare Date, DateTime, Time and TimeWithZone with Infinity
4 12
     This allows to create date/time ranges with one infinite bound.
5 13
     Example:
6  activesupport/lib/active_support/core_ext/string/conversions.rb
@@ -32,11 +32,7 @@ def to_time(form = :utc)
32 32
   #   "2012-12-13".to_date #=> Thu, 13 Dec 2012
33 33
   #   "12/13/2012".to_date #=> ArgumentError: invalid date
34 34
   def to_date
35  
-    unless blank?
36  
-      date_values = ::Date._parse(self, false).values_at(:year, :mon, :mday)
37  
-
38  
-      ::Date.new(*date_values)
39  
-    end
  35
+    ::Date.parse(self, false) unless blank?
40 36
   end
41 37
 
42 38
   # Converts a string to a DateTime value.
1  activesupport/test/core_ext/string_ext_test.rb
@@ -307,6 +307,7 @@ def test_string_to_datetime
307 307
   def test_string_to_date
308 308
     assert_equal Date.new(2005, 2, 27), "2005-02-27".to_date
309 309
     assert_nil "".to_date
  310
+    assert_equal Date.new(Date.today.year, 2, 3), "Feb 3rd".to_date
310 311
   end
311 312
 end
312 313
 

0 notes on commit ebd27d5

Please sign in to comment.
Something went wrong with that request. Please try again.