Skip to content

Commit

Permalink
Add support to CNPJ
Browse files Browse the repository at this point in the history
  • Loading branch information
franciscomxs committed Dec 4, 2018
1 parent 88e3dd1 commit eef1195
Show file tree
Hide file tree
Showing 4 changed files with 74 additions and 0 deletions.
11 changes: 11 additions & 0 deletions doc/unreleased/default/cnpj.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# Faker::CNPJ

Brazilian CNPJ valid random generator.

```ruby
Faker::CNPJ.number
#=> "00000000000"

Faker::CNPJ.formatted
#=> "000.000.000-00"
```
45 changes: 45 additions & 0 deletions lib/faker/default/cnpj.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
# frozen_string_literal: true

module Faker
class CNPJ < Faker::Base
attr_accessor :digits

def initialize
@digits = Array.new(8).map { Faker::Config.random.rand(0..9) }.concat([0, 0, 0, 1])
end

def number
@number ||= [*digits, first_digit, last_digit].join
end

def formatted
@formatted ||= '%s.%s.%s/%s-%s' % number.scan(/(\d{2})(\d{3})(\d{3})(\d{4})(\d{2})/).flatten
end

private

def first_digit
values = [5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2]
sum = digits.map.with_index { |v, i| v * values[i] }.inject(&:+)
result = sum % 11
result < 2 ? 0 : 11 - result
end

def last_digit
values = [6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2]
sum = [*digits, first_digit].map.with_index { |v, i| v * values[i] }.inject(&:+)
result = sum % 11
result < 2 ? 0 : 11 - result
end

class << self
def number
new.number
end

def formatted
new.formatted
end
end
end
end
17 changes: 17 additions & 0 deletions test/faker/default/test_faker_cnpj.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# frozen_string_literal: true

require_relative '../../test_helper'

class TestFakerCNPJ < Test::Unit::TestCase
def setup
@tester = Faker::CNPJ.new
end

def test_number
assert_equal(14, @tester.number.length)
end

def test_formatted
assert @tester.formatted.match(/\d{2}\.\d{3}\.\d{3}\/\d{4}-\d{2}/)
end
end
1 change: 1 addition & 0 deletions unreleased_README.md
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,7 @@ gem 'faker', :git => 'https://github.com/stympy/faker.git', :branch => 'master'
- [Faker::Cannabis](doc/unreleased/default/cannabis.md)
- [Faker::ChileRut](doc/unreleased/default/chile_rut.md)
- [Faker::ChuckNorris](doc/unreleased/default/chuck_norris.md)
- [Faker::CNPJ](doc/unreleased/default/cnpj.md)
- [Faker::Code](doc/unreleased/default/code.md)
- [Faker::Coffee](doc/unreleased/default/coffee.md)
- [Faker::Coin](doc/unreleased/default/coin.md)
Expand Down

0 comments on commit eef1195

Please sign in to comment.