Class: SIIChile::Rut

Inherits:
Object
  • Object
show all
Defined in:
lib/sii_chile/rut.rb

Overview

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(rut) ⇒ Rut

Returns a new instance of Rut


7
8
9
10
11
# File 'lib/sii_chile/rut.rb', line 7

def initialize(rut)
  @rut = rut.to_s.strip
  @number = @rut.gsub(/[^0-9K]/i,'')[0...-1]
  @code = @rut[-1].upcase
end

Instance Attribute Details

#codeObject (readonly)

Returns the value of attribute code


5
6
7
# File 'lib/sii_chile/rut.rb', line 5

def code
  @code
end

#numberObject (readonly)

Returns the value of attribute number


4
5
6
# File 'lib/sii_chile/rut.rb', line 4

def number
  @number
end

Instance Method Details

#calculated_codeObject


25
26
27
28
29
30
31
32
33
34
# File 'lib/sii_chile/rut.rb', line 25

def calculated_code
  all_codes = (0..9).to_a + ['K']
  reverse_digits = @number.split('').reverse
  factors = (2..7).to_a * 2
  partial_sum = reverse_digits.zip(factors).inject(0) do |r, a|
    digit, factor = *a
    r += digit.to_i * factor
  end
  all_codes[(11 - partial_sum%11)%11].to_s
end

#code_valid?Boolean

Returns:

  • (Boolean)

21
22
23
# File 'lib/sii_chile/rut.rb', line 21

def code_valid?
  @code == calculated_code
end

#format(opts = {}) ⇒ Object


40
41
42
43
44
45
46
# File 'lib/sii_chile/rut.rb', line 40

def format(opts={})
  delimiter = opts[:delimiter] || '.'
  with_dash = opts[:with_dash].nil? ? true : opts[:with_dash]
  formatted_rut = number_with_delimiter(delimiter)
  formatted_rut << '-' if with_dash
  formatted_rut << @code
end

#number_with_delimiter(delimiter = '.') ⇒ Object


36
37
38
# File 'lib/sii_chile/rut.rb', line 36

def number_with_delimiter(delimiter='.')
  @number.to_s.gsub(/(\d)(?=(\d\d\d)+(?!\d))/, "\\1#{delimiter}")
end

#size_valid?Boolean

Returns:

  • (Boolean)

17
18
19
# File 'lib/sii_chile/rut.rb', line 17

def size_valid?
  @number.size <= 8
end

#to_sObject


48
# File 'lib/sii_chile/rut.rb', line 48

def to_s; format; end

#valid?Boolean

Returns:

  • (Boolean)

13
14
15
# File 'lib/sii_chile/rut.rb', line 13

def valid?
  size_valid? && code_valid?
end