Skip to content

Instantly share code, notes, and snippets.

@henryhamon
Created August 14, 2008 18:34
Show Gist options
  • Save henryhamon/5465 to your computer and use it in GitHub Desktop.
Save henryhamon/5465 to your computer and use it in GitHub Desktop.
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