Module: Philiprehberger::RandomData

Defined in:
lib/philiprehberger/random_data.rb,
lib/philiprehberger/random_data/data.rb,
lib/philiprehberger/random_data/version.rb

Defined Under Namespace

Classes: Error

Constant Summary collapse

FIRST_NAMES =
%w[
  James Mary Robert Patricia John Jennifer Michael Linda David Elizabeth
  William Barbara Richard Susan Joseph Jessica Thomas Sarah Charles Karen
  Christopher Lisa Daniel Nancy Matthew Betty Mark Sandra Donald Ashley
  Steven Emily Paul Kimberly Andrew Donna Joshua Michelle Kenneth Dorothy
  Kevin Carol Brian Amanda George Melissa Edward Deborah Ronald Stephanie
].freeze
LAST_NAMES =
%w[
  Smith Johnson Williams Brown Jones Garcia Miller Davis Rodriguez Martinez
  Hernandez Lopez Gonzalez Wilson Anderson Thomas Taylor Moore Jackson Martin
  Lee Perez Thompson White Harris Sanchez Clark Ramirez Lewis Robinson Walker
  Young Allen King Wright Scott Torres Nguyen Hill Flores Green Adams Nelson
  Baker Hall Rivera Campbell Mitchell Carter Roberts Gomez Phillips Evans
].freeze
LOREM_WORDS =
%w[
  lorem ipsum dolor sit amet consectetur adipiscing elit sed do eiusmod
  tempor incididunt ut labore et dolore magna aliqua enim ad minim veniam
  quis nostrud exercitation ullamco laboris nisi aliquip ex ea commodo
  consequat duis aute irure in reprehenderit voluptate velit esse cillum
  fugiat nulla pariatur excepteur sint occaecat cupidatat non proident sunt
  culpa qui officia deserunt mollit anim id est
].freeze
EMAIL_DOMAINS =
%w[
  example.com test.com mail.test sample.org demo.net
].freeze
PHONE_FORMATS =
[
  '(###) ###-####',
  '###-###-####',
  '+1 ### ### ####'
].freeze
STREET_SUFFIXES =
%w[St Ave Blvd Dr Ln Rd Way Ct Pl Cir].freeze
CITIES =
%w[
  Springfield Riverside Fairview Madison Clinton Franklin Greenville Bristol
  Oakland Burlington Salem Georgetown Manchester Arlington Jackson Lexington
].freeze
STATES =
%w[
  AL AK AZ AR CA CO CT DE FL GA HI ID IL IN IA KS KY LA ME MD
  MA MI MN MS MO MT NE NV NH NJ NM NY NC ND OH OK OR PA RI SC
  SD TN TX UT VT VA WA WV WI WY
].freeze
COMPANY_SUFFIXES =
%w[Inc LLC Corp Group Solutions Systems Labs Technologies].freeze
URL_SCHEMES =
%w[https http].freeze
URL_TLDS =
%w[com org net io dev app co].freeze
VERSION =
'0.3.0'

Class Method Summary collapse

Class Method Details

.addressHash

Generate a random address

Returns:

  • (Hash)

    address with street, city, state, zip



157
158
159
160
161
162
163
164
# File 'lib/philiprehberger/random_data.rb', line 157

def self.address
  number = rand(100..9999)
  street = "#{LAST_NAMES.sample} #{STREET_SUFFIXES.sample}"
  city = CITIES.sample
  state = STATES.sample
  zip = format('%05d', rand(10_000..99_999))
  { street: "#{number} #{street}", city: city, state: state, zip: zip }
end

.booleanBoolean

Generate a random boolean

Returns:

  • (Boolean)

    true or false



114
115
116
# File 'lib/philiprehberger/random_data.rb', line 114

def self.boolean
  [true, false].sample
end

.colorString

Generate a random hex color

Returns:

  • (String)

    hex color string



186
187
188
# File 'lib/philiprehberger/random_data.rb', line 186

def self.color
  format('#%06x', rand(0x000000..0xFFFFFF))
end

.companyString

Generate a random company name

Returns:

  • (String)

    company name



169
170
171
# File 'lib/philiprehberger/random_data.rb', line 169

def self.company
  "#{LAST_NAMES.sample} #{COMPANY_SUFFIXES.sample}"
end

.date(range = nil) ⇒ Date

Generate a random date within a range

Parameters:

  • range (Range<Date>) (defaults to: nil)

    range of dates

Returns:

  • (Date)

    random date



99
100
101
102
103
104
105
106
107
108
109
# File 'lib/philiprehberger/random_data.rb', line 99

def self.date(range = nil)
  if range
    start_date = range.min
    end_date = range.max
    days = (end_date - start_date).to_i
    start_date + rand(0..days)
  else
    today = Date.today
    today - rand(0..365)
  end
end

.emailString

Generate a random email address

Returns:

  • (String)

    email address



36
37
38
39
40
41
42
# File 'lib/philiprehberger/random_data.rb', line 36

def self.email
  fn = first_name.downcase
  ln = last_name.downcase
  domain = EMAIL_DOMAINS.sample
  separator = ['.', '_', ''].sample
  "#{fn}#{separator}#{ln}@#{domain}"
end

.first_nameString

Generate a random first name

Returns:

  • (String)

    first name



22
23
24
# File 'lib/philiprehberger/random_data.rb', line 22

def self.first_name
  FIRST_NAMES.sample
end

.float(range = 0.0..1.0) ⇒ Float

Generate a random float within a range

Parameters:

  • range (Range) (defaults to: 0.0..1.0)

    range of floats

Returns:

  • (Float)

    random float



89
90
91
92
93
# File 'lib/philiprehberger/random_data.rb', line 89

def self.float(range = 0.0..1.0)
  min = range.min.to_f
  max = range.max.to_f
  min + (rand * (max - min))
end

.hex(length = 16) ⇒ String

Generate a random hex string

Parameters:

  • length (Integer) (defaults to: 16)

    number of hex characters

Returns:

  • (String)

    hex string



122
123
124
# File 'lib/philiprehberger/random_data.rb', line 122

def self.hex(length = 16)
  SecureRandom.hex((length / 2) + 1)[0, length]
end

.integer(range = 0..100) ⇒ Integer

Generate a random integer within a range

Parameters:

  • range (Range) (defaults to: 0..100)

    range of integers

Returns:

  • (Integer)

    random integer



81
82
83
# File 'lib/philiprehberger/random_data.rb', line 81

def self.integer(range = 0..100)
  rand(range)
end

.ipv4String

Generate a random IPv4 address

Returns:

  • (String)

    IPv4 address



150
151
152
# File 'lib/philiprehberger/random_data.rb', line 150

def self.ipv4
  Array.new(4) { rand(1..254) }.join('.')
end

.last_nameString

Generate a random last name

Returns:

  • (String)

    last name



29
30
31
# File 'lib/philiprehberger/random_data.rb', line 29

def self.last_name
  LAST_NAMES.sample
end

.nameString

Generate a random full name

Returns:

  • (String)

    first and last name



15
16
17
# File 'lib/philiprehberger/random_data.rb', line 15

def self.name
  "#{first_name} #{last_name}"
end

.paragraph(sentences: rand(3..7)) ⇒ String

Generate a random paragraph

Parameters:

  • sentences (Integer) (defaults to: rand(3..7))

    number of sentences

Returns:

  • (String)

    paragraph of sentences



73
74
75
# File 'lib/philiprehberger/random_data.rb', line 73

def self.paragraph(sentences: rand(3..7))
  Array.new(sentences) { sentence }.join(' ')
end

.password(length: 16, symbols: true) ⇒ String

Generate a random password

Parameters:

  • length (Integer) (defaults to: 16)

    password length

  • symbols (Boolean) (defaults to: true)

    include symbols

Returns:

  • (String)

    random password



195
196
197
198
199
# File 'lib/philiprehberger/random_data.rb', line 195

def self.password(length: 16, symbols: true)
  chars = [('a'..'z'), ('A'..'Z'), ('0'..'9')].flat_map(&:to_a)
  chars += %w[! @ # $ % ^ & * _ - + =] if symbols
  Array.new(length) { chars.sample }.join
end

.phoneString

Generate a random phone number

Returns:

  • (String)

    formatted phone number



47
48
49
50
# File 'lib/philiprehberger/random_data.rb', line 47

def self.phone
  format = PHONE_FORMATS.sample
  format.gsub('#') { rand(10).to_s }
end

.pick(array) ⇒ Object

Pick a random element from an array

Parameters:

  • array (Array)

    source array

Returns:

  • (Object)

    random element

Raises:



130
131
132
133
134
# File 'lib/philiprehberger/random_data.rb', line 130

def self.pick(array)
  raise Error, 'Array must not be empty' if array.nil? || array.empty?

  array.sample
end

.sample(array, n) ⇒ Array

Sample n random elements from an array

Parameters:

  • array (Array)

    source array

  • n (Integer)

    number of elements

Returns:

  • (Array)

    random elements

Raises:



141
142
143
144
145
# File 'lib/philiprehberger/random_data.rb', line 141

def self.sample(array, n)
  raise Error, 'Array must not be empty' if array.nil? || array.empty?

  array.sample(n)
end

.sentence(words: rand(5..15)) ⇒ String

Generate a random sentence

Parameters:

  • words (Integer) (defaults to: rand(5..15))

    number of words

Returns:

  • (String)

    sentence with capitalized first word and period



63
64
65
66
67
# File 'lib/philiprehberger/random_data.rb', line 63

def self.sentence(words: rand(5..15))
  selected = Array.new(words) { LOREM_WORDS.sample }
  selected[0] = selected[0].capitalize
  "#{selected.join(' ')}."
end

.timestamp(range = nil) ⇒ Time

Generate a random timestamp

Parameters:

  • range (Range<Time>) (defaults to: nil)

    optional time range

Returns:

  • (Time)

    random time



205
206
207
208
209
210
211
212
213
# File 'lib/philiprehberger/random_data.rb', line 205

def self.timestamp(range = nil)
  if range
    start_time = range.min
    end_time = range.max
    Time.at(start_time.to_f + (rand * (end_time.to_f - start_time.to_f)))
  else
    Time.now - rand(0..(365 * 24 * 60 * 60))
  end
end

.urlString

Generate a random URL

Returns:

  • (String)

    URL



176
177
178
179
180
181
# File 'lib/philiprehberger/random_data.rb', line 176

def self.url
  scheme = URL_SCHEMES.sample
  domain = "#{LAST_NAMES.sample.downcase}#{rand(1..999)}"
  tld = URL_TLDS.sample
  "#{scheme}://#{domain}.#{tld}"
end

.uuidString

Generate a random UUID v4

Returns:

  • (String)

    UUID string



55
56
57
# File 'lib/philiprehberger/random_data.rb', line 55

def self.uuid
  SecureRandom.uuid
end

.weighted_pick(array, weights:) ⇒ Object

Pick a random element from array using the matching probability weights.

Each index in array has a corresponding non-negative numeric weight in weights. The element is selected via cumulative-weight sampling, where elements with higher weights are proportionally more likely to be returned.

Parameters:

  • array (Array)

    source array

  • weights (Array<Numeric>)

    non-negative weights, one per element

Returns:

  • (Object)

    one element from array chosen proportionally to its weight

Raises:

  • (ArgumentError)

    if array and weights differ in length, if any weight is negative, or if every weight is zero



70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/philiprehberger/random_data/data.rb', line 70

def self.weighted_pick(array, weights:)
  raise ArgumentError, 'array and weights must be the same length' if array.length != weights.length
  raise ArgumentError, 'weights must all be numeric' unless weights.all?(Numeric)
  raise ArgumentError, 'weights must all be non-negative' if weights.any?(&:negative?)

  total = weights.sum
  raise ArgumentError, 'weights must not all be zero' if total.zero?

  threshold = rand * total
  cumulative = 0.0
  array.each_with_index do |element, index|
    cumulative += weights[index]
    return element if threshold < cumulative
  end

  array.last
end