Module: Run
Class Method Summary collapse
-
.for(model, attribute, randomize = true) ⇒ Object
Generar un run valido segun reglas chilenas y que ademas es unico para el modelo entregado.
-
.format(run, digit = false) ⇒ Object
Formatea un run.
-
.generate ⇒ Object
Generar un run valido segun reglas chilenas.
-
.remove_format(run, digit = false) ⇒ Object
Quita el formato de un run.
Instance Method Summary collapse
-
#valid?(run) ⇒ Boolean
Revisa si el run entregado es valido, el run debe incluir el digito verificador.
Class Method Details
.for(model, attribute, randomize = true) ⇒ Object
Generar un run valido segun reglas chilenas y que ademas es unico para el modelo entregado
40 41 42 43 44 45 46 47 48 49 50 51 |
# File 'lib/run_cl/run.rb', line 40 def self.for model, attribute, randomize=true valid_rut = randomize ? self.generate : '111111111' model_class = model.to_s.camelize.constantize if model_class.respond_to?(:table_name) && ActiveRecord::Base.connection.table_exists?(model_class.table_name) while model_class.where(attribute.to_sym => valid_rut).any? do valid_rut = self.generate end else puts "not ActiveRecord::Base.connection.table_exists? model.to_s" end valid_rut end |
.format(run, digit = false) ⇒ Object
Formatea un run
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
# File 'lib/run_cl/run.rb', line 5 def self.format run, digit=false return nil if run.nil? pos = 0 run.reverse reverse = "" run.reverse.gsub("-", "").gsub(".", "").split('').each_with_index do |c, index| reverse += c if index == 0 reverse += '-' elsif (pos == 3) reverse += "." pos = 0 end pos += 1 end if digit reverse.reverse[0..-3] else reverse.reverse end end |
.generate ⇒ Object
Generar un run valido segun reglas chilenas
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 |
# File 'lib/run_cl/run.rb', line 54 def self.generate run = (rand * 20000000).round + 5000000 suma = 0 mul = 2 run.to_s.reverse.split('').each do |i| suma = suma + i.to_i * mul if mul == 7 mul = 2 else mul += 1 end end res = suma % 11 if res == 1 return "#{run}k" elsif res == 0 return "#{run}0" else return "#{run}#{11-res}" end end |
.remove_format(run, digit = false) ⇒ Object
Quita el formato de un run
29 30 31 32 33 34 35 36 37 |
# File 'lib/run_cl/run.rb', line 29 def self.remove_format run, digit=false return nil if run.nil? if digit run.gsub("-", "").gsub(".", "")[0..-3] else run.gsub("-", "").gsub(".", "") end end |
Instance Method Details
#valid?(run) ⇒ Boolean
Revisa si el run entregado es valido, el run debe incluir el digito verificador
79 80 81 82 83 84 85 86 87 88 89 |
# File 'lib/run_cl/run.rb', line 79 def valid? run if run run_copy = run.clone run_copy = run_copy.match(/^(\d+)\.{1}\d{3}\.{1}\d{3}-{1}(\d|k|K)$|^(\d+)\d{6}\-{1}(\d|k|K)|^(\d+)\d{6}(\d|k|K)$/i).to_s return false unless run_copy run_copy = remove_format(run_copy) check_run run_copy.chop, run_copy.last else false end end |