Tiny gem that may be useful for generating strings of digits that satisy the Luhn algorithm
Ruby
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Failed to load latest commit information.
lib
spec
.document
.gitignore
Gemfile
Gemfile.lock
LICENSE
README.rdoc
Rakefile
VERSION
luhnacy.gemspec

README.rdoc

luhnacy

A tiny (hopefully) gem that will automate some of the painful tasks of generating / validating strings of numbers based on the Luhn algorithm (e.g. credit card numbers, ID numbers).

Usage

To require:

require 'luhnacy'

Generic ValidationGeneration

To validate:

Luhnacy.valid?('49927398716')

To generate a string of 10 digits that satisfies the Luhn algorithm:

valid_string = Luhnacy.generate(10)

To generate a string of 10 digits that does not satisfy Luhn algorithm:

invalid_string = Luhnacy.generate(10, :invalid => true)

To generate a string of 10 digits that satisfies Luhn and starts with predefined characters:

Luhnacy.generate(10, :prefix => '12345') #=> "1234597480"

Named Generators/Validators

There are named validators and generators for Visa, Mastercard and American Express credit cards. Note: Visa validation/generation only works for 16-digit credit card numbers.

Also, there is also a named generator for the National Provider Identifier (thanks to Taylor Yelverton) used in the US to identify health care providers - see example usage section.

Example usage (mastercard)

To validate a mastercard:

Luhnacy.mastercard?("5176290135048779")

To generate a mastercard number that satisfies Luhn:

Luhnacy.mastercard #=> "5151199732615386"

To generate a master card number that does not satisfy Luhn:

Luhnacy.mastercard(:invalid => true)

Similar usage exists for Visa, American Express and NPI:

Luhnacy.visa
Luhnacy.visa?

Luhnacy.amex
Luhnacy.amex?

Luhnacy.doctor_npi
Luhnacy.doctor_npi?

Planned changes

At some point it may make sense to store the patterns for the named generator in a seperate class/module or even in a YAML file. This will be driven by the need for additional named generators. If a YAML file is used, then the very next release may also include the ability to pass Luhnacy a custom YAML file for generating/validating strings.

Note on Patches/Pull Requests

  • Fork the project.

  • Make your feature addition or bug fix.

  • Add tests for it. This is important so I don't break it in a future version unintentionally.

  • Commit, do not mess with rakefile, version, or history. (if you want to have your own version, that is fine but bump version in a commit by itself I can ignore when I pull)

  • Send me a pull request. Bonus points for topic branches.

Sources

Copyright

Copyright © 2010 Rory McKinley. See LICENSE for details.