Class: Faker::Base

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

Direct Known Subclasses

Address, Company, Internet, Lorem, Name, PhoneNumber

Class Method Summary collapse

Class Method Details

.bothify(string) ⇒ Object



36
37
38
# File 'lib/faker.rb', line 36

def bothify(string)
  letterify(numerify(string))
end

.fetch(key) ⇒ Object

Helper for the common approach of grabbing a translation with an array of values and selecting one of them.



42
43
44
# File 'lib/faker.rb', line 42

def fetch(key)
  translate("faker.#{key}").sample
end

.flexible(key) ⇒ Object



67
68
69
# File 'lib/faker.rb', line 67

def flexible(key)
  @flexible_key = key
end

.letterify(letter_string) ⇒ Object



32
33
34
# File 'lib/faker.rb', line 32

def letterify(letter_string)
  letter_string.gsub(/\?/) { ('A'..'Z').to_a.sample }
end

.method_missing(m, *args, &block) ⇒ Object

You can add whatever you want to the locale file, and it will get caught here. E.g., in your locale file, create a

name:
  girls_name: ["Alice", "Cheryl", "Tatiana"]

Then you can call Faker::Name.girls_name and it will act like #first_name



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

def method_missing(m, *args, &block)
  # Use the alternate form of translate to get a nil rather than a "missing translation" string
  if translation = translate(:faker)[@flexible_key][m]
    translation.respond_to?(:sample) ? translation.sample : translation
  else
    super
  end
end

.numerify(number_string) ⇒ Object

make sure numerify results doesn’t start with a zero



28
29
30
# File 'lib/faker.rb', line 28

def numerify(number_string)
  number_string.sub(/#/) { (rand(9)+1).to_s }.gsub(/#/) { rand(10).to_s }
end

.parse(key) ⇒ Object

Load formatted strings from the locale, “parsing” them into method calls that can be used to generate a formatted translation: e.g., “#first_name #last_name”.



49
50
51
# File 'lib/faker.rb', line 49

def parse(key)
  fetch(key).scan(/#\{([A-Za-z]+\.)?([^\}]+)\}([^#]+)?/).map {|kls, meth, etc| (kls ? Faker.const_get(kls.chop) : self).send(meth) + etc.to_s }.join
end

.translate(*args) ⇒ Object

Call I18n.translate with our configured locale if no locale is specified



55
56
57
58
59
60
61
62
63
64
65
# File 'lib/faker.rb', line 55

def translate(*args)
  opts = args.last.is_a?(Hash) ? args.pop : {}
  opts[:locale] ||= Faker::Config.locale
  opts[:throw] = true
  I18n.translate(*(args.push(opts)))
rescue
  # Super-simple fallback -- fallback to en if the
  # translation was missing.  If the translation isn't
  # in en either, then it will raise again.
  I18n.translate(*(args.push(opts.merge(:locale => :en))))
end