run_cl 1.0.7 → 1.0.8

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.
Files changed (3) hide show
  1. data/lib/run_cl.rb +88 -2
  2. data/lib/run_cl/version.rb +1 -1
  3. metadata +2 -2
data/lib/run_cl.rb CHANGED
@@ -1,7 +1,93 @@
1
- require '/run_cl/run'
1
+ # require '/run_cl/run'
2
2
  require '/run_cl/run_validator'
3
3
  require '/run_cl/version'
4
4
 
5
5
  module RunCl
6
- # Your code goes here...
6
+ module Run
7
+ extend self
8
+
9
+ # Formatea un run
10
+ def self.format run
11
+ pos = 0
12
+ run.reverse
13
+ reverse = ""
14
+ run.reverse.gsub("-", "").gsub(".", "").split('').each_with_index do |c, index|
15
+ reverse += c
16
+ if index == 0
17
+ reverse += '-'
18
+ elsif (pos == 3)
19
+ reverse += "."
20
+ pos = 0
21
+ end
22
+ pos += 1
23
+ end
24
+ reverse.reverse
25
+ end
26
+
27
+ # Quita el formato de un run
28
+ def self.remove_format run
29
+ run.gsub("-", "").gsub(".", "")
30
+ end
31
+
32
+ # Generar un run valido segun reglas chilenas y que ademas es unico para el modelo entregado
33
+ def self.for model, attribute, randomize=true
34
+ valid_rut = randomize ? self.generate : '111111111'
35
+
36
+ if ActiveRecord::Base.connection.table_exists? model.to_s
37
+ model_class = model.to_s.camelize.constantize
38
+ while model_class.where(attribute.to_sym => valid_rut).any? do valid_rut = self.generate end
39
+ end
40
+
41
+ valid_rut
42
+ end
43
+
44
+ # Generar un run valido segun reglas chilenas
45
+ def self.generate seed = nil
46
+ run = (rand * 20000000).round + 5000000 unless seed.presence
47
+
48
+ suma = 0
49
+ mul = 2
50
+ run.to_s.reverse.split('').each do |i|
51
+ suma = suma + i.to_i * mul
52
+ if mul == 7
53
+ mul = 2
54
+ else
55
+ mul += 1
56
+ end
57
+ end
58
+ res = suma % 11
59
+
60
+ if res == 1
61
+ return "#{run}k"
62
+ elsif res == 0
63
+ return "#{run}0"
64
+ else
65
+ return "#{run}#{11-res}"
66
+ end
67
+ end
68
+
69
+ # Revisa si el run y digito entregado es valido
70
+ def self.check_run run, digit
71
+ return false if run.empty?
72
+ return false if digit.empty?
73
+
74
+ factor = 2
75
+ suma = 0
76
+ i = run.length - 1
77
+
78
+ while i >= 0
79
+ factor = 2 if factor > 7
80
+ suma = suma + ( run[i] ).to_i * factor.to_i
81
+ factor += 1
82
+ i -= 1
83
+ end
84
+
85
+ dv = 11 - ( suma % 11 )
86
+ dv = 0 if dv == 11
87
+ dv = "k" if dv == 10
88
+
89
+ return true if dv.to_s == digit.downcase
90
+ false
91
+ end
92
+ end
7
93
  end
@@ -1,3 +1,3 @@
1
1
  module RunCl
2
- VERSION = "1.0.7"
2
+ VERSION = "1.0.8"
3
3
  end
metadata CHANGED
@@ -5,8 +5,8 @@ version: !ruby/object:Gem::Version
5
5
  segments:
6
6
  - 1
7
7
  - 0
8
- - 7
9
- version: 1.0.7
8
+ - 8
9
+ version: 1.0.8
10
10
  platform: ruby
11
11
  authors:
12
12
  - mespina