Last active
December 15, 2015 11:55
-
-
Save jesperronn/12fe09b4e487588a2d52 to your computer and use it in GitHub Desktop.
Danish CPR numbers: strip ssn dashes from numbers when saving, so that they are used consistently throughout the application
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Formatting and validation of Danish CPR number | |
# when saving we will throw away the dash "-" in the SSN and show it when retrieving | |
# | |
# Custom retrieval of formatted value: This is done by the method | |
# `formatted_cpr`. Use that in your views if you need it | |
# | |
# or in extreme cases you can override the getter method and call `formatted_cpr` | |
# | |
# Strategies for saving of unformatted value: | |
# 1. use either `base.after_validation` to hook into callbacks. This is a little annoying | |
# for unit testing since you have to validate. But ok to use | |
# | |
# 2. use custom setter method `cpr=`, which works during typecasting of value. | |
# | |
# Both examples are included here | |
# | |
module CprFormatting | |
def self.included(base) | |
base.extend ClassMethods | |
base.validates :cpr, format: /\d{6}-?\d\w\w\d/ | |
# Strategy #1: (use only one of them) | |
# base.after_validation :strip_ssn_dash | |
end | |
module ClassMethods | |
end | |
# Strategy #2: (use only one of them) | |
def cpr=(val) | |
self[:cpr] = val && val.delete('-') | |
end | |
# def strip_ssn_dash | |
# self.cpr = cpr.delete('-') | |
# end | |
def formatted_cpr | |
if cpr.present? | |
"#{cpr[0..5]}-#{cpr[6..9]}" | |
else | |
'' | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment