Skip to content
This repository
Browse code

Merge pull request #11574 from jetthoughts/11552_rescue_on_invalid_in…

…et_assign

Fix assign ip address with invalid values raise exception
  • Loading branch information...
commit a4d4af4083d4b41c348f7e707874aedfa1d8a3cd 2 parents f04b75f + 0aa95a7
Yves Senn authored August 14, 2013
18  activerecord/CHANGELOG.md
Source Rendered
... ...
@@ -1,3 +1,21 @@
  1
+*   Assign inet/cidr attribute with `nil` value for invalid address.
  2
+
  3
+    Example:
  4
+
  5
+        record = User.new
  6
+
  7
+        record.logged_in_from_ip # is type of an inet or a cidr
  8
+
  9
+        # Before:
  10
+        record.logged_in_from_ip = 'bad ip address' # raise exception
  11
+
  12
+        # After:
  13
+        record.logged_in_from_ip = 'bad ip address' # do not raise exception
  14
+        record.logged_in_from_ip # => nil
  15
+        record.logged_in_from_ip_before_type_cast # => 'bad ip address'
  16
+
  17
+    *Paul Nikitochkin*
  18
+
1 19
 *   `add_to_target` now accepts a second optional `skip_callbacks` argument
2 20
 
3 21
     If truthy, it will skip the :before_add and :after_add callbacks.
6  activerecord/lib/active_record/connection_adapters/postgresql/cast.rb
@@ -100,7 +100,11 @@ def string_to_cidr(string)
100 100
           if string.nil?
101 101
             nil
102 102
           elsif String === string
103  
-            IPAddr.new(string)
  103
+            begin
  104
+              IPAddr.new(string)
  105
+            rescue ArgumentError
  106
+              nil
  107
+            end
104 108
           else
105 109
             string
106 110
           end
14  activerecord/test/cases/adapters/postgresql/datatype_test.rb
@@ -558,6 +558,20 @@ def test_invalid_hex_string
558 558
     assert_raise(ActiveRecord::StatementInvalid) { assert @first_bit_string.save }
559 559
   end
560 560
 
  561
+  def test_invalid_network_address
  562
+    @first_network_address.cidr_address = 'invalid addr'
  563
+    assert_nil @first_network_address.cidr_address
  564
+    assert_equal 'invalid addr', @first_network_address.cidr_address_before_type_cast
  565
+    assert @first_network_address.save
  566
+
  567
+    @first_network_address.reload
  568
+
  569
+    @first_network_address.inet_address = 'invalid addr'
  570
+    assert_nil @first_network_address.inet_address
  571
+    assert_equal 'invalid addr', @first_network_address.inet_address_before_type_cast
  572
+    assert @first_network_address.save
  573
+  end
  574
+
561 575
   def test_update_oid
562 576
     new_value = 567890
563 577
     @first_oid.obj_id = new_value

0 notes on commit a4d4af4

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