Module: FFakerTW::ModuleUtils

Instance Method Summary collapse

Methods included from RandomUtils

#fetch_sample, #rand, #shuffle

Instance Method Details

#const_missing(const_name) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
# File 'lib/ffakerTW/utils/module_utils.rb', line 15

def const_missing(const_name)
  if const_name =~ /[a-z]/ # Not a constant, probably a class/module name.
    super const_name
  else
    mod_name = ancestors.first.to_s.split('::').last
    data_path = "#{FFakerTW::BASE_LIB_PATH}/ffakerTW/data/#{underscore(mod_name)}/#{underscore(const_name.to_s)}"
    data = k File.read(data_path, mode: 'r:UTF-8').split("\n")
    const_set const_name, data
    data
  end
end

#k(arg) ⇒ Object



11
12
13
# File 'lib/ffakerTW/utils/module_utils.rb', line 11

def k(arg)
  FFakerTW::ArrayUtils.const_array(arg)
end

#luhn_check(number) ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/ffakerTW/utils/module_utils.rb', line 40

def luhn_check(number)
  multiplications = []

  number.split(//).each_with_index do |digit, i|
    multiplications << i.even? ? digit.to_i * 2 : digit.to_i
  end

  sum = 0
  multiplications.each do |num|
    num.to_s.each_byte do |character|
      sum += character.chr.to_i
    end
  end

  control_digit = (sum % 10).zero? ? 0 : (sum / 10 + 1) * 10 - sum
  control_digit.to_s
end

#underscore(string) ⇒ Object



27
28
29
30
31
32
33
# File 'lib/ffakerTW/utils/module_utils.rb', line 27

def underscore(string)
  string.gsub(/::/, '/')
        .gsub(/([A-Z]+)([A-Z][a-z])/, '\1_\2')
        .gsub(/([a-z\d])([A-Z])/, '\1_\2')
        .tr('-', '_')
        .downcase
end

#unique(max_retries = 10_000) ⇒ Object



35
36
37
# File 'lib/ffakerTW/utils/module_utils.rb', line 35

def unique(max_retries = 10_000)
  @unique_generator ||= FFakerTW::UniqueUtils.new(self, max_retries)
end