File: module_utils.rb

package info (click to toggle)
ruby-ffaker 2.23.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 3,776 kB
  • sloc: ruby: 12,788; makefile: 8; sh: 1
file content (58 lines) | stat: -rw-r--r-- 1,526 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# frozen_string_literal: true

require_relative 'array_utils'
require_relative 'random_utils'
require_relative 'unique_utils'

module FFaker
  module ModuleUtils
    include RandomUtils

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

    def const_missing(const_name)
      if const_name.match?(/[a-z]/) # Not a constant, probably a class/module name.
        super const_name
      else
        mod_name = ancestors.first.to_s.split('::').last
        data_path = "#{FFaker::BASE_LIB_PATH}/ffaker/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

    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

    def unique(max_retries = 10_000)
      FFaker::UniqueUtils.add_instance(self, max_retries)
    end

    # http://en.wikipedia.org/wiki/Luhn_algorithm
    def luhn_check(number)
      multiplications = []

      number.chars.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
  end
end