diff --git a/lib/area/string.rb b/lib/area/string.rb index 5a7fe90..1f6fdd9 100644 --- a/lib/area/string.rb +++ b/lib/area/string.rb @@ -27,12 +27,14 @@ def to_area # # Returns a String of converted area codes or zipcodes. def to_region(options = {}) - if self.to_s.length == 3 # an area code - row = Area.area_codes.find {|row| row.first == self.to_s } + code = self.to_s + code = code[0..4] if code.match(/^\d{5}-?\d{4}$/) + if code.length == 3 # an area code + row = Area.area_codes.find {|row| row.first == code } return row.last if row - elsif self.to_s.length == 5 - if row = Area.zip_codes.find {|row| row.first == self.to_s } - if row.first == self.to_s + elsif code.length == 5 + if row = Area.zip_codes.find {|row| row.first == code } + if row.first == code if options[:city] return row[1] elsif options[:state] diff --git a/test/unit/area_test.rb b/test/unit/area_test.rb index 6173932..67c571d 100644 --- a/test/unit/area_test.rb +++ b/test/unit/area_test.rb @@ -63,6 +63,13 @@ def test_that_it_converts_zip_code_to_region assert_equal "Brooklyn, NY", "11211".to_region end + def test_that_it_supports_nine_digits_for_zipcodes + assert_equal "Brooklyn, NY", "11211-1111".to_region + assert_equal "Brooklyn, NY", "112111111".to_region + assert_equal "Brooklyn", "11211-1111".to_region(:city => true) + assert_equal "NY", "11211-1111".to_region(:state => true) + end + def test_that_it_supports_options_for_zipcodes assert_equal "Brooklyn", "11211".to_region(:city => true) assert_equal "NY", "11211".to_region(:state => true) @@ -101,6 +108,9 @@ def test_that_it_returns_false_for_daylight_savings_time_nonobservance def test_that_it_handles_incorrect_zips assert_equal [], "9888".to_zip assert_raises(ArgumentError) { "9888".to_region } + assert_raises(ArgumentError) { "988888".to_region } + assert_raises(ArgumentError) { "98888-44444".to_region } + assert_raises(ArgumentError) { "9888844444".to_region } assert_raises(ArgumentError) { "9888".to_area } assert_raises(ArgumentError) { "9888".to_gmt_offset } assert_raises(ArgumentError) { "9888".to_dst }