Created
August 14, 2008 18:34
-
-
Save henryhamon/5465 to your computer and use it in GitHub Desktop.
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
class Cpf | |
def verifica_cpf(cpf = nil) | |
return false if cpf.nil? | |
if int_cpf(c[0.8], 1) != c[9] || int_cpf(c[0..9], 0) != c[10] | |
false | |
else | |
true | |
end | |
end | |
def int_cpf(c, pos) | |
som = 0 | |
for n in c.to_s.split('').collect {|i| i.to_i } | |
pos += 1 | |
som += n * pos | |
end | |
som % 11 | |
end | |
end | |
module ActiveRecord | |
module Validations | |
module ClassMethods | |
def validate_cpf(*attr_names) | |
cpf_validator = Cpf.new | |
configuration = { | |
:message => 'invalido', | |
:on => :save | |
} | |
validates_each(attr_names, configuration) do |record, attr_name,value| | |
if !cpf_validator.verifica_cpf(value) | |
record.errors.add(attr_name, configuration[:message]) | |
end | |
end | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment