Created
March 30, 2021 15:08
-
-
Save crystianwendel/d49002f479afb4cc124bdd58da4d1e2b to your computer and use it in GitHub Desktop.
Classe pra validar número do CNS / Cartão Nacional de Saúde / Cartão SUS
This file contains hidden or 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
# frozen_string_literal: true | |
## | |
# Inspired by http://www.yanaga.com.br/2012/06/validacao-do-cns-cartao-nacional-de.html and https://github.com/fnando/cpf_cnpj | |
# | |
# @example Basic usage | |
# | |
# CNS.new("187507943600018").valid? # true | |
# CNS.new("187 5079 4360 0018").valid? # false | |
# CNS.new("187507943600010").valid? # false | |
# CNS.new("187507943600010").formatted # 187507943600010 | |
# CNS.new("187507943600018").formatted # 187 5079 4360 0018 | |
# | |
# @todo add option to validation to be strict or not | |
class CNS | |
def initialize(number) | |
@number = number | |
end | |
def formatted | |
return @number.insert(11, ' ').insert(7, ' ').insert(3, ' ') if valid? | |
@number | |
end | |
def valid? | |
if @number =~ /\A[1-2]\d{10}00[0-1]\d\z/ || @number =~ /\A[7-9]\d{14}\z/ | |
return CNS.weighted_sum(@number) % 11 == 0 | |
end | |
false | |
end | |
def self.weighted_sum(s) | |
soma = 0 | |
s.each_char.with_index do |c, i| | |
soma += c.to_i * (15 - i) | |
end | |
soma | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment