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).
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"
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:
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?
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.
Copyright © 2010 Rory McKinley. See LICENSE for details.