Address verification for Ruby and Rails
Switch branches/tags
Nothing to show
Clone or download

README.md

MainStreet

Address verification for Ruby and Rails

🌎 Supports international addresses

Installation

Add this line to your application’s Gemfile:

gem 'mainstreet'

Full Verification

By default, bad street numbers, units, and postal codes may pass verification. For full verification, get an account with SmartyStreets. The free plan supports 250 lookups per month for US addresses, and plans for international addresses start at $7. To use it, set:

ENV["SMARTY_STREETS_AUTH_ID"] = "auth-id"
ENV["SMARTY_STREETS_AUTH_TOKEN"] = "auth-token"

How to Use

Check an address with:

address = "1600 Pennsylvania Ave NW, Washington DC 20500"
verifier = MainStreet::AddressVerifier.new(address)
verifier.success?

If verification fails, get the failure message with:

verifier.failure_message

Get details about the result with:

verifier.result

Get the latitude and longitude with:

verifier.latitude
verifier.longitude

Active Record

For Active Record models, use:

class User < ApplicationRecord
  validates_address fields: [:street, :street2, :city, :state, :postal_code]
end

For performance, the address is only verified if at least one of the fields changes. The order should be the same as if you were to write the address out.

Geocode the address with:

class User < ApplicationRecord
  validates_address geocode: true, ...
end

The latitude and longitude fields are used by default. Specify the fields with:

class User < ApplicationRecord
  validates_address geocode: {latitude: :lat, longitude: :lon}, ...
end

Empty addresses are not verified. To require an address, add your own validation.

class User < ApplicationRecord
  validates :street, presence: true
end

SmartyStreets

With SmartyStreets, you must pass the country for non-US addresses.

MainStreet::AddressVerifier.new(address, country: "France")

Here’s the list of supported countries. You can pass the name, ISO-3, ISO-2, or ISO-N code (like France, FRA, FR, or 250).

Note: You’ll also need to use a fork of Geocoder until this PR is merged.

gem 'geocoder', github: 'ankane/geocoder', branch: 'smarty_streets_international'

For Active Record, use:

class User < ApplicationRecord
  validates_address country: "France", ...
end

Or use a proc to make it dynamic

class User < ApplicationRecord
  validates_address country: -> { country }, ...
end

Data Privacy

We recommend encrypting street information and postal code (at the very least) for user addresses. Check out this article for more details.

class User < ApplicationRecord
  attr_encrypted :street, key: ...
  attr_encrypted :postal_code, key: ...
end

Upgrading

0.2.0

See the upgrade guide

History

View the changelog

Contributing

Everyone is encouraged to help improve this project. Here are a few ways you can help: