Module: ZFaker::ModuleUtils

Included in:
ZFaker, Internet, Name
Defined in:
lib/zfaker/utils/module_utils.rb

Overview

Module ModuleUtils

Instance Method Summary collapse

Instance Method Details

#const_missing(const_name) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/zfaker/utils/module_utils.rb', line 9

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 = "#{ZFaker::BASE_LIB_PATH}/zfaker/data/#{underscore(mod_name)}/#{underscore(const_name.to_s)}"
    reader = k File.read(data_path).split("\n")
    arrout = []
    reader.each do |x|
      cut = x.split(' ')
      if cut.size > 1 && cut[0].integer?
        weight = cut[0].to_i
        element = cut[1..-1].join(' ')
        element = '' if element == '<blank>'
      else
        weight = 1
        element = cut[0..-1].join(' ')
      end
      weight.times { arrout.push(element) }
    end
    const_set const_name, arrout
    arrout
  end
end

#k(arg) ⇒ Object



6
7
# File 'lib/zfaker/utils/module_utils.rb', line 6

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

#underscore(string) ⇒ Object



34
35
36
37
38
39
40
# File 'lib/zfaker/utils/module_utils.rb', line 34

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_sample(arr) ⇒ Object



42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/zfaker/utils/module_utils.rb', line 42

def unique_sample(arr)
  sample = ''
  collisions = 0
  loop do
    sample = yield
    break unless arr.include? sample
    collisions += 1
    fail 'Too Many Collisions: ' + collisions.to_s if collisions > (arr.size + 50) * 10
  end
  arr.push sample
  sample
end