Class: QuickFaker

Inherits:
Object
  • Object
show all
Defined in:
lib/quick_faker.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(locale = 'en-GB', debug: false) ⇒ QuickFaker

Returns a new instance of QuickFaker.



18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/quick_faker.rb', line 18

def initialize(locale='en-GB', debug: false)

  @debug = debug
  Faker::Config.locale = locale
  s = File.join(File.dirname(__FILE__), '..', 'data', 'faker.yaml')

  a = YAML.load(File.read(s))
  @topics = a.to_h
  @a = a.flat_map(&:last)

  load_methods(a)

end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method_name, *args) ⇒ Object (private)



125
126
127
# File 'lib/quick_faker.rb', line 125

def method_missing(method_name, *args)
  lookup(method_name, *args)
end

Instance Attribute Details

#aObject (readonly)

Returns the value of attribute a.



16
17
18
# File 'lib/quick_faker.rb', line 16

def a
  @a
end

#topicsObject (readonly)

Returns the value of attribute topics.



16
17
18
# File 'lib/quick_faker.rb', line 16

def topics
  @topics
end

Instance Method Details

#lookup(s, context = nil) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/quick_faker.rb', line 32

def lookup(s, context=nil)

  found = @h[s.to_sym]
  puts 'found: ' + found.inspect if @debug

  if found and found[0].is_a? Array

    h = found.map {|x| x.last[/[^:]+(?=\.)/].downcase.to_sym}.zip(found.map(&:first)).to_h
    if context then
      h[context.to_sym].call
    elsif h.keys.include? :name
      h[:name].call
    else
      raise 'provide context! options: ' + h.keys.map(&:to_s).join(', ') \
          + "\n   try e.g. lookup(:#{s}, :#{h.keys.first})"
    end
  elsif found
    found[0].call
  else
    puts ('*' + s.to_s + '* not found').warning
    puts ('try: ').info
    @a.grep /#{s}/i
  end
end

#lookup2(s) ⇒ Object



57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/quick_faker.rb', line 57

def lookup2(s)

  found = @h[s.to_sym]
  if found and found[0].is_a? Array then
    found.map(&:last)
  elsif found[0]
    found.last
  else
    puts ('*' + s.to_s + '* not found').warning
    puts ('try: ').info
    @a.grep(/#{s}/i)[/[^\.]+$/].uniq.sort
  end

end

#options(s = nil) ⇒ Object



76
77
78
79
80
81
82
83
84
85
# File 'lib/quick_faker.rb', line 76

def options(s=nil)

  return query s if s

  @h.map do |key, a|
    a2 = a[0].is_a?(Array) ? a.map(&:last) : a.last
    [key, a2]
  end.sort_by(&:first)

end

#query(topic) ⇒ Object



72
73
74
# File 'lib/quick_faker.rb', line 72

def query(topic)
  @topics[topic.to_s.capitalize]
end

#to_hObject



87
88
89
# File 'lib/quick_faker.rb', line 87

def to_h()
  @h
end