Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Danish CPR numbers: strip ssn dashes from numbers when saving, so that they are used consistently throughout the application
# 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
You can’t perform that action at this time.