The GoingPostal mixin provides classes with postcode formatting and validation methods.
$ gem install going_postal
GoingPostal can be used as a mixin:
class Address include GoingPostal attr_accessor :number, :street, :city, :postcode, :country_code def initialize(number, street, :city, postcode, country_code="GB") self.number = number self.street = street self.city = city self.postcode = postcode self.country_code = country_code end def postcode=(value) @postcode = format_postcode(value) end def valid? number && street && city && postcode_valid? end end
or as a namespaced collection of methods:
GoingPostal.postcode?("sl41eg", "GB") #=> "SL4 1EG" GoingPostal.postcode?("200378001", "US") #=> "20037-8001"
The methods available are #postcode? for checking validity, and format_postcode which returns a formatted postcode. Both take arguments of a string, the postcode, and a two letter country code. If the class has a #country_code method, the country_code argument on the provided methods becomes optional. If the class also has one of #postcode, #post_code, #zipcode, #zip_code, or #zip, the string argument on the provided methods becomes optional.
postcode? is aliased as post_code?, zip?, zipcode?, zip_code?, valid_postcode?, valid_post_code?, valid_zip?, valid_zipcode?, valid_zip_code?, postcode_valid?, post_code_valid?, zip_valid?, zipcode_valid? and zip_code_valid? The alias valid? is also available directly on the GoingPostal module.
format_postcode is aliased as format_post_code, format_zip, format_zipcode, and format_zip_code.
(The MIT License)
Copyright © 2011 Global Personals, Ltd.
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.