asd
Testing textmate blog stuff
Rails “personnummer” validator
The Swedish equivalent to USAs “social security number”’s is called “personnummer” in Swedish, a “personnummer” is looks like this:
YYYYMMDD-PPKX
Where YYYYMMDD is the date the person was born. PP are two random numbers and K indicates the sex of the person (odd for males and even for women), X is simply a control number to check whether it looks valid or not. The control number is calculated as follow (thanks to susning.nu).
7 3 0 2 3 1 - 4 9 1
* 2 1 2 1 2 1 2 1 2
14 3 0 2 6 1 8 9 2 = 1+4+3+0+2+6+1+8+9+2 = 36.
The sum, in this case 36 is then round up to nearest ten.
So the control number would in this case be 4.
Enough theory, in one of my clients projects I had to check whether the “personnummer” was valid or not. I wrote up this validator, it’s not nice but i does it’s job.
Just modify the column name, in my case “personnummer” to fit your needs and add this to your model.
class User < ActiveRecord::Base # ... validate :validate_reservation # ... def validate_personnummer # Kontrollera antal siffror i personnummret. if personnummer.size != 12 errors.add_to_base "Personnummret innehåller fel antal siffror. (ÅÅÅÅMMDDXXXX)" end # Räkna ut kontrollsiffran sum = tmp = 0 (2..10).each do |i| if i % 2 == 0 if (tmp = 2 * personnummer[i,1].to_i) > 9 sum = sum + tmp - 9 else sum = sum + tmp end else sum = sum + personnummer[i,1].to_i end end if (sum % 10) != 0 if (10 - (sum % 10)) != personnummer[11,3].to_i errors.add_to_base 'Personnummret måste vara riktigt.' end else if personnummer[11,3] != 0 errors.add_to_base 'Personnummret måste vara riktigt.' end end end end
Calculate years since (age) in rails.
Sometimes you need need to know the years since a date, maybe to find out the age of a person, and the solution in Ruby on Rails is pretty straight forward:
(Date - Date).to_i / 365
Example usage in my ‘User’ model.
# Find out the age of the person. # self.social_security_number[0..7] = YYYYMMDD (Swedish "personnummer") def age (Date.today - Date.parse(self.social_security_number[0..7])).to_i / 365 end
Rails find current URI
To find the current URI (Everything after domain name) in Ruby on Rails:
# Request: http://localhost/hello/world <%=request.request_uri-%> # would render /hello/world
Rails test snippet
map.resources :users do |user| user.resources :photos, :member => {:icon => :get, :thumbnail => :get, :avatar => :get } user.resources :friends user.resources :messages user.resources :guestbook end