brcpfcnpj 2.0.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
data/CHANGELOG ADDED
File without changes
data/MIT-LICENSE ADDED
@@ -0,0 +1,20 @@
1
+ Copyright (c) 2008 [name of plugin creator]
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining
4
+ a copy of this software and associated documentation files (the
5
+ "Software"), to deal in the Software without restriction, including
6
+ without limitation the rights to use, copy, modify, merge, publish,
7
+ distribute, sublicense, and/or sell copies of the Software, and to
8
+ permit persons to whom the Software is furnished to do so, subject to
9
+ the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be
12
+ included in all copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/README ADDED
@@ -0,0 +1 @@
1
+ Aqui vai o readme
data/Rakefile ADDED
@@ -0,0 +1,100 @@
1
+ require 'rubygems'
2
+ require 'rake'
3
+ require 'rake/testtask'
4
+ require 'rake/rdoctask'
5
+ require 'rake/packagetask'
6
+ require 'rake/gempackagetask'
7
+ require 'rake/contrib/sshpublisher'
8
+ require 'spec'
9
+ require 'spec/rake/spectask'
10
+ require File.join(File.dirname(__FILE__), 'lib', 'brcpfcnpj', 'version')
11
+
12
+ PKG_BUILD = ENV['PKG_BUILD'] ? '.' + ENV['PKG_BUILD'] : ''
13
+ PKG_NAME = 'brcpfcnpj'
14
+ PKG_VERSION = BrCpfCnpj::VERSION::STRING + PKG_BUILD
15
+ PKG_FILE_NAME = "#{PKG_NAME}-#{PKG_VERSION}"
16
+
17
+ RELEASE_NAME = "REL #{PKG_VERSION}"
18
+
19
+ RUBY_FORGE_PROJECT = "brcpfcnpj"
20
+ RUBY_FORGE_USER = "tapajos"
21
+
22
+ desc "Default Task"
23
+ task :default => [ :spec ]
24
+
25
+ desc "Run all specs"
26
+ Spec::Rake::SpecTask.new do |t|
27
+ t.spec_files = FileList['spec/**/*_spec.rb']
28
+ end
29
+
30
+ task :test do
31
+ system("rake spec")
32
+ end
33
+
34
+ #Generate the RDoc documentation
35
+ Rake::RDocTask.new { |rdoc|
36
+ rdoc.rdoc_dir = 'doc'
37
+ rdoc.title = "Brazilian Rails -- Data"
38
+ rdoc.options << '--line-numbers' << '--inline-source' << '-A cattr_accessor=object'
39
+ rdoc.options << '--charset' << 'utf-8'
40
+ rdoc.template = "#{ENV['template']}.rb" if ENV['template']
41
+ rdoc.rdoc_files.include('README', 'CHANGELOG')
42
+ rdoc.rdoc_files.include('lib/**/*')
43
+ }
44
+
45
+
46
+ # Create compressed packages
47
+ spec = Gem::Specification.new do |s|
48
+ s.platform = Gem::Platform::RUBY
49
+ s.name = PKG_NAME
50
+ s.summary = "brcpfcnpj é uma das gems que compoem o Brazilian Rails"
51
+ s.description = %q{brcpfcnpj é uma das gems que compoem o Brazilian Rails}
52
+ s.version = PKG_VERSION
53
+
54
+ s.authors = ["Marcos Tapajós", "Celestino Gomes", "Andre Kupkosvki", "Vinícius Teles", "Cássio Marques"]
55
+ s.email = "tapajos@gmail.com"
56
+ s.rubyforge_project = "brcpfcnpj"
57
+ s.homepage = "http://www.improveit.com.br/software_livre/brazilian_rails"
58
+
59
+ s.add_dependency('actionpack', '>= 1.13.6')
60
+ s.add_dependency('activesupport', '>= 1.4.2')
61
+
62
+ s.has_rdoc = true
63
+ s.requirements << 'none'
64
+ s.require_path = 'lib'
65
+
66
+ s.files = [ "Rakefile", "README", "CHANGELOG", "MIT-LICENSE" ]
67
+ s.files = s.files + Dir.glob( "lib/**/*" ).delete_if { |item| item.include?( "\.svn" ) }
68
+ s.files = s.files + Dir.glob( "test/**/*" ).delete_if { |item| item.include?( "\.svn" ) }
69
+ end
70
+
71
+ Rake::GemPackageTask.new(spec) do |p|
72
+ p.gem_spec = spec
73
+ p.need_tar = true
74
+ p.need_zip = true
75
+ end
76
+
77
+
78
+ # desc "Publish the API documentation"
79
+ # task :pgem => [:package] do
80
+ # Rake::SshFilePublisher.new("wrath.rubyonrails.org", "public_html/gems/gems", "pkg", "#{PKG_FILE_NAME}.gem").upload
81
+ # end
82
+ #
83
+ # desc "Publish the API documentation"
84
+ # task :pdoc => [:rdoc] do
85
+ # Rake::SshDirPublisher.new("wrath.rubyonrails.org", "public_html/am", "doc").upload
86
+ # end
87
+ #
88
+
89
+ desc "Publish the release files to RubyForge."
90
+ task :release => [ :package ] do
91
+ require 'rubyforge'
92
+ require 'rake/contrib/rubyforgepublisher'
93
+
94
+ packages = %w( gem tgz zip ).collect{ |ext| "pkg/#{PKG_NAME}-#{PKG_VERSION}.#{ext}" }
95
+
96
+ rubyforge = RubyForge.new
97
+ rubyforge.configure
98
+ rubyforge.login
99
+ rubyforge.add_release("brazilian-rails", PKG_NAME, "REL #{PKG_VERSION}", *packages)
100
+ end
@@ -0,0 +1,45 @@
1
+ # Representa um numero de CNPJ. Objetos da classe Cnpj recebem strings representando numeros de cnpj e verificam a validade destes numeros usando dois criterios:
2
+ # 1. O formato da string, que deve seguir o padrao xx.xxx.xxx/xxxx-xx, onde 'x' pode ser qualquer digito de 0 a 9 e os tracos (-), barra (/) e pontos (.) *sao opcionais*.
3
+ # 2. O conteudo numerico desta string, que eh validado atraves do calculo do 'modulo 11' dos digitos que compoe a string.
4
+ #
5
+ # Caso o conteudo da string obedeca ao formato especificado acima, o mesmo sera formatado para obedecer ao padrao xx.xxx.xxx/xxxx-xx
6
+ #
7
+ # Eh importante observar que caso voce associe um valor de cnpj invalido ao seu model, o mesmo passara automaticamente a ser invalido, o que impede que valores de cpf incorretos sejam salvos no banco de dados.
8
+ #
9
+ # Como usar a classe Cnpj no seu ActiveRecord:
10
+ #
11
+ # Suponha que temos um model Empresa, com um atributo 'cnpj'
12
+ # que voce quer usar como um numero de documento para cnpj. Basta usar o
13
+ # metodo <tt>usar_como_cnpj</tt>, assim:
14
+ #
15
+ # class Empresa < ActiveRecord::Base
16
+ # usar_como_cnpj :cnpj
17
+ # end
18
+ #
19
+ # Agora voce pode usar o atributo para cnpj da seguinte forma:
20
+ #
21
+ # e = Empresa.new
22
+ # e.cnpj = "69103604000160"
23
+ # puts e.cnpj # ==> 69.103.604/0001-60
24
+ # e.cnpj.valido? # ==> true
25
+ # e.cnpj_valido? # ==> true
26
+ #
27
+ # e = Empresa.new(:cnpj => "69.103.604/0001-60")
28
+ # puts e.cnpj # ==> 69.103.604/0001-60
29
+ #
30
+ # e = Empresa.new
31
+ # e.cnpj = Cnpj.new("691036040001-60")
32
+ # puts e.cnpj # ==> 69.103.604/0001-60
33
+ #
34
+ # e = Empresa.new
35
+ # e.cnpj = "12343" # ==> um cnpj invalido
36
+ # puts e.valid? # ==> false
37
+ # e.save # ==> false
38
+ # e.errors.on(:cnpj) # ==> 'numero invalido'
39
+ #
40
+ # c = Cnpj.new("69103604000160")
41
+ # e.cnpj = "69.103.604/0001-60"
42
+ # c == e.cnpj # ==> true
43
+ class Cnpj
44
+ include CpfCnpj
45
+ end
@@ -0,0 +1,51 @@
1
+ # Representa um numero de CPF. Objetos da classe Cpf recebem strings representando
2
+ # numeros de cpf e verificam a validade destes numeros usando dois criterios:
3
+ # 1. O formato da string, que deve seguir o padrao xxx.xxx.xxx-xx, onde 'x' pode ser qualquer digito de 0 a 9 e os tracos (-) e pontos (.) *sao opcionais*.
4
+ # 2. O conteudo numerico desta string, que eh validado atraves do calculo do 'modulo 11' dos digitos que compoe a string.
5
+ #
6
+ # Caso o conteudo da string obedeca ao formato especificado acima, o mesmo sera formatado para obedecer ao padrao xxx.xxx.xxx-xx
7
+ #
8
+ # Eh importante observar que caso voce associe um valor de cpf invalido ao seu model, o mesmo passara automaticamente a ser invalido, o que impede que valores de cpf incorretos sejam salvos no banco de dados.
9
+ #
10
+ # Como usar a classe Cpf no seu ActiveRecord:
11
+ #
12
+ # Suponha que temos um model Pessoa, com um atributo 'cpf'
13
+ # que voce quer usar como um numero de documento para cpf. Basta usar o
14
+ # metodo <tt>usar_como_cpf</tt>, assim:
15
+ #
16
+ # class Pessoa < ActiveRecord::Base
17
+ # usar_como_cpf :cpf
18
+ # end
19
+ #
20
+ # O atributo que sera usado como cpf pode ter qualquer nome e nao apenas 'cpf'
21
+ #
22
+ # Agora voce pode usar o atributo para cpf da seguinte forma:
23
+ #
24
+ # p = Pessoa.new
25
+ # p.cpf = "11144477735"
26
+ # puts p.cpf # ==> 111.444.777-35
27
+ # p.cpf.valido? # ==> true
28
+ # p.cpf_valido? # ==> true
29
+ #
30
+ # p = Pessoa.new(:cpf => "111.444.777-35")
31
+ # puts p.cpf # ==> 111.444.777-35
32
+ #
33
+ # p = Pessoa.new
34
+ # p.cpf = Cpf.new("111444777-35")
35
+ # puts p.cpf # ==> 111.444.777-35
36
+ #
37
+ # p = Pessoa.new
38
+ # p.cpf = "12345" # ==> um cpf invalido
39
+ # puts p.valid? # ==> false
40
+ # p.save # ==> false
41
+ # p.errors.on(:cpf) # ==> 'numero invalido'
42
+ #
43
+ # c = Cpf.new("11144477735")
44
+ # p.cpf = "111.444.777-35"
45
+ # c == p.cpf # ==> true
46
+ #
47
+ class Cpf
48
+ include CpfCnpj
49
+ end
50
+
51
+
@@ -0,0 +1,89 @@
1
+ module CpfCnpj
2
+ attr_reader :numero
3
+
4
+ def initialize(numero)
5
+ @numero = numero
6
+ @match = self.instance_of?(Cpf) ? @numero =~ CPF_REGEX : @numero =~ CNPJ_REGEX
7
+ @numero_puro = $1
8
+ @para_verificacao = $2
9
+ @numero = (@match ? format_number! : nil)
10
+ end
11
+
12
+ def to_s
13
+ @numero || ""
14
+ end
15
+
16
+ def ==(outro_doc)
17
+ self.numero == outro_doc.numero
18
+ end
19
+
20
+ # Verifica se o numero possui o formato correto e se
21
+ # constitui um numero de documento valido, dependendo do seu
22
+ # tipo (Cpf ou Cnpj).
23
+ def valido?
24
+ return false unless @match
25
+ verifica_numero
26
+ end
27
+
28
+ private
29
+ DIVISOR = 11
30
+
31
+ CPF_LENGTH = 11
32
+ CPF_REGEX = /(\d{3}\.?\d{3}\.?\d{3})-?(\d{2})/
33
+ CPF_ALGS_1 = [10, 9, 8, 7, 6, 5, 4, 3, 2]
34
+ CPF_ALGS_2 = [11, 10, 9, 8, 7, 6, 5, 4, 3, 2]
35
+
36
+ CNPJ_LENGTH = 14
37
+ CNPJ_REGEX = /(\d{2}\.?\d{3}\.?\d{3}\/?\d{4})-?(\d{2})/ # <= 11.222.333/0001-XX
38
+ CNPJ_ALGS_1 = [5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2]
39
+ CNPJ_ALGS_2 = [6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2]
40
+
41
+
42
+ def verifica_numero
43
+ limpo = @numero.gsub(/[\.\/-]/, "")
44
+ if self.instance_of? Cpf
45
+ return false if limpo.length != 11
46
+ elsif self.instance_of? Cnpj
47
+ return false if limpo.length != 14
48
+ end
49
+ return false if limpo.scan(/\d/).sort.join == limpo
50
+ primeiro_verificador = primeiro_digito_verificador
51
+ segundo_verificador = segundo_digito_verificador(primeiro_verificador)
52
+ verif = primeiro_verificador + segundo_verificador
53
+ verif == @para_verificacao
54
+ end
55
+
56
+ def multiplica_e_soma(algs, numero_str)
57
+ multiplicados = []
58
+ numero_str.scan(/\d{1}/).each_with_index { |e, i| multiplicados[i] = e.to_i * algs[i] }
59
+ multiplicados.inject { |s,e| s + e }
60
+ end
61
+
62
+ def digito_verificador(resto)
63
+ resto < 2 ? 0 : DIVISOR - resto
64
+ end
65
+
66
+ def primeiro_digito_verificador
67
+ array = self.instance_of?(Cpf) ? CPF_ALGS_1 : CNPJ_ALGS_1
68
+ soma = multiplica_e_soma(array, @numero_puro)
69
+ digito_verificador(soma%DIVISOR).to_s
70
+ end
71
+
72
+ def segundo_digito_verificador(primeiro_verificador)
73
+ array = self.instance_of?(Cpf) ? CPF_ALGS_2 : CNPJ_ALGS_2
74
+ soma = multiplica_e_soma(array, @numero_puro + primeiro_verificador)
75
+ digito_verificador(soma%DIVISOR).to_s
76
+ end
77
+
78
+ def format_number!
79
+ if self.instance_of? Cpf
80
+ @numero =~ /(\d{3})\.?(\d{3})\.?(\d{3})-?(\d{2})/
81
+ @numero = "#{$1}.#{$2}.#{$3}-#{$4}"
82
+ else
83
+ @numero =~ /(\d{2})\.?(\d{3})\.?(\d{3})\/?(\d{4})-?(\d{2})/
84
+ @numero = "#{$1}.#{$2}.#{$3}/#{$4}-#{$5}"
85
+ end
86
+ end
87
+
88
+ end
89
+
@@ -0,0 +1,77 @@
1
+ module CpfCnpjActiveRecord #:nodoc:
2
+ def self.included(base) #:nodoc:
3
+ base.extend ClassMethods
4
+ end
5
+ module ClassMethods #:nodoc:
6
+ def usar_como_cpf(*args) #:nodoc:
7
+ unless args.size.zero?
8
+ args.each do |name|
9
+ composed_of name, :class_name => 'Cpf', :mapping => [name.to_s, "numero"], :allow_nil => true do
10
+ Cpf.new(name[:numero])
11
+ end
12
+ name = name.to_s
13
+ module_eval <<-ADICIONANDO_METODOS_PARA_CPF
14
+ validate :#{name}_valido?
15
+
16
+ def #{name}_valido?
17
+ value = read_attribute('#{name}')
18
+ if !value.nil? && value.strip != '' && !#{name}.nil? && !#{name}.valido?
19
+ self.errors.add('#{name}', 'numero invalido')
20
+ end
21
+ end
22
+
23
+ def #{name}=(value)
24
+ if value.nil?
25
+ write_attribute('#{name}', nil)
26
+ elsif value.kind_of?(Cpf)
27
+ write_attribute('#{name}', value.numero)
28
+ else
29
+ begin
30
+ write_attribute('#{name}', value)
31
+ rescue
32
+ @#{name} = value
33
+ end
34
+ end
35
+ end
36
+ ADICIONANDO_METODOS_PARA_CPF
37
+ end
38
+ end
39
+ end
40
+
41
+ def usar_como_cnpj(*args) #:nodoc:
42
+ unless args.size.zero?
43
+ args.each do |name|
44
+ composed_of name, :class_name => 'Cnpj', :mapping => [name.to_s, "numero"], :allow_nil => true do
45
+ Cnpj.new(name[:numero])
46
+ end
47
+
48
+ name = name.to_s
49
+ module_eval <<-ADICIONANDO_METODOS_PARA_CNPJ
50
+ validate :#{name}_valido?
51
+
52
+ def #{name}_valido?
53
+ value = read_attribute('#{name}')
54
+ if !value.nil? && value.strip != '' && !#{name}.nil? && !#{name}.valido?
55
+ self.errors.add('#{name}', 'numero invalido')
56
+ end
57
+ end
58
+
59
+ def #{name}=(value)
60
+ if value.nil?
61
+ write_attribute('#{name}', nil)
62
+ elsif value.kind_of?(Cnpj)
63
+ write_attribute('#{name}', value.numero)
64
+ else
65
+ begin
66
+ write_attribute('#{name}', value)
67
+ rescue
68
+ @#{name} = value
69
+ end
70
+ end
71
+ end
72
+ ADICIONANDO_METODOS_PARA_CNPJ
73
+ end
74
+ end
75
+ end
76
+ end
77
+ end
@@ -0,0 +1,5 @@
1
+ module BrCpfCnpj
2
+ module VERSION #:nodoc:
3
+ STRING = "2.0.7"
4
+ end
5
+ end
data/lib/brcpfcnpj.rb ADDED
@@ -0,0 +1,12 @@
1
+ $:.unshift(File.dirname(__FILE__)) unless
2
+ $:.include?(File.dirname(__FILE__)) || $:.include?(File.expand_path(File.dirname(__FILE__)))
3
+
4
+ %w(cpf_cnpj cnpj cpf cpf_cnpj_activerecord).each {|req| require File.dirname(__FILE__) + "/brcpfcnpj/#{req}"}
5
+
6
+ %w(rubygems active_record activesupport).each {|req| require req }
7
+
8
+ ActiveRecord::Base.send :include, CpfCnpjActiveRecord
9
+
10
+ module BrCpfCnpj
11
+ end
12
+
metadata ADDED
@@ -0,0 +1,86 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: brcpfcnpj
3
+ version: !ruby/object:Gem::Version
4
+ version: 2.0.7
5
+ platform: ruby
6
+ authors:
7
+ - "Marcos Tapaj\xC3\xB3s"
8
+ - Celestino Gomes
9
+ - Andre Kupkosvki
10
+ - "Vin\xC3\xADcius Teles"
11
+ - "C\xC3\xA1ssio Marques"
12
+ autorequire:
13
+ bindir: bin
14
+ cert_chain: []
15
+
16
+ date: 2008-09-23 00:00:00 -03:00
17
+ default_executable:
18
+ dependencies:
19
+ - !ruby/object:Gem::Dependency
20
+ name: actionpack
21
+ type: :runtime
22
+ version_requirement:
23
+ version_requirements: !ruby/object:Gem::Requirement
24
+ requirements:
25
+ - - ">="
26
+ - !ruby/object:Gem::Version
27
+ version: 1.13.6
28
+ version:
29
+ - !ruby/object:Gem::Dependency
30
+ name: activesupport
31
+ type: :runtime
32
+ version_requirement:
33
+ version_requirements: !ruby/object:Gem::Requirement
34
+ requirements:
35
+ - - ">="
36
+ - !ruby/object:Gem::Version
37
+ version: 1.4.2
38
+ version:
39
+ description: "brcpfcnpj \xC3\xA9 uma das gems que compoem o Brazilian Rails"
40
+ email: tapajos@gmail.com
41
+ executables: []
42
+
43
+ extensions: []
44
+
45
+ extra_rdoc_files: []
46
+
47
+ files:
48
+ - Rakefile
49
+ - README
50
+ - CHANGELOG
51
+ - MIT-LICENSE
52
+ - lib/brcpfcnpj
53
+ - lib/brcpfcnpj/cnpj.rb
54
+ - lib/brcpfcnpj/cpf.rb
55
+ - lib/brcpfcnpj/cpf_cnpj.rb
56
+ - lib/brcpfcnpj/cpf_cnpj_activerecord.rb
57
+ - lib/brcpfcnpj/version.rb
58
+ - lib/brcpfcnpj.rb
59
+ has_rdoc: true
60
+ homepage: http://www.improveit.com.br/software_livre/brazilian_rails
61
+ post_install_message:
62
+ rdoc_options: []
63
+
64
+ require_paths:
65
+ - lib
66
+ required_ruby_version: !ruby/object:Gem::Requirement
67
+ requirements:
68
+ - - ">="
69
+ - !ruby/object:Gem::Version
70
+ version: "0"
71
+ version:
72
+ required_rubygems_version: !ruby/object:Gem::Requirement
73
+ requirements:
74
+ - - ">="
75
+ - !ruby/object:Gem::Version
76
+ version: "0"
77
+ version:
78
+ requirements:
79
+ - none
80
+ rubyforge_project: brcpfcnpj
81
+ rubygems_version: 1.2.0
82
+ signing_key:
83
+ specification_version: 2
84
+ summary: "brcpfcnpj \xC3\xA9 uma das gems que compoem o Brazilian Rails"
85
+ test_files: []
86
+