repo stringlengths 5 92 | file_url stringlengths 80 287 | file_path stringlengths 5 197 | content stringlengths 0 32.8k | language stringclasses 1 value | license stringclasses 7 values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:37:27 2026-01-04 17:58:21 | truncated bool 2 classes |
|---|---|---|---|---|---|---|---|---|
faker-ruby/faker | https://github.com/faker-ruby/faker/blob/a4d5e503edda970fc085e942018ee235622bfb11/test/faker/movies/test_faker_the_room.rb | test/faker/movies/test_faker_the_room.rb | # frozen_string_literal: true
require_relative '../../test_helper'
class TestFakerRoom < Test::Unit::TestCase
def setup
@tester = Faker::Movies::TheRoom
end
def test_actor
assert_match(/\w+/, @tester.actor)
end
def test_character
assert_match(/\w+/, @tester.character)
end
def test_location
assert_match(/\w+/, @tester.location)
end
def test_quote
assert_match(/\w+/, @tester.quote)
end
end
| ruby | MIT | a4d5e503edda970fc085e942018ee235622bfb11 | 2026-01-04T15:37:50.353881Z | false |
faker-ruby/faker | https://github.com/faker-ruby/faker/blob/a4d5e503edda970fc085e942018ee235622bfb11/test/faker/movies/test_faker_lord_of_the_rings.rb | test/faker/movies/test_faker_lord_of_the_rings.rb | # frozen_string_literal: true
require_relative '../../test_helper'
class TestFakerLordOfTheRings < Test::Unit::TestCase
def setup
@tester = Faker::Movies::LordOfTheRings
end
def test_character
assert_match(/\w+/, @tester.character)
end
def test_location
assert_match(/\w+/, @tester.location)
end
def test_quote
assert_match(/\w+/, @tester.quote)
end
end
| ruby | MIT | a4d5e503edda970fc085e942018ee235622bfb11 | 2026-01-04T15:37:50.353881Z | false |
faker-ruby/faker | https://github.com/faker-ruby/faker/blob/a4d5e503edda970fc085e942018ee235622bfb11/test/faker/movies/test_faker_tron.rb | test/faker/movies/test_faker_tron.rb | # frozen_string_literal: true
require_relative '../../test_helper'
class TestFakerTron < Test::Unit::TestCase
CHARACTER_COUNT = 16
GAME_COUNT = 14
LOCATION_COUNT = 12
PROGRAM_COUNT = 9
TAGLINE_COUNT = 5
USER_COUNT = 6
VEHICLE_COUNT = 5
def setup
@tester = Faker::Movies::Tron
end
def test_character
assert_match(/\w+/, @tester.character)
end
def test_game
assert_match(/\w+/, @tester.game)
end
def test_location
assert_match(/\w+/, @tester.location)
end
def test_program
assert_match(/\w+/, @tester.program)
end
def test_quote
assert_match(/\w+/, @tester.quote)
end
# test good match
def test_quote_random_character
assert_match(/\w+/, @tester.quote(character: 'dr_lora_baines'))
end
# test good alternate spelling match
def test_quote_random_character_alt_spelling
assert_match(/\w+/, @tester.quote(character: 'Laura Baines'))
end
# test error on no match
def test_quote_invalid
assert_raise ArgumentError do
@tester.quote(character: 'Leto Atreides')
end
end
def test_tagline
assert_match(/\w+/, @tester.tagline)
end
def test_user
assert_match(/\w+/, @tester.user)
end
def test_vehicle
assert_match(/\w+/, @tester.vehicle)
end
def test_characters
characters = @tester.characters
assert_kind_of Array, characters
assert_equal characters.length, CHARACTER_COUNT
end
def test_games
games = @tester.games
assert_kind_of Array, games
assert_equal games.length, GAME_COUNT
end
def test_locations
locations = @tester.locations
assert_kind_of Array, locations
assert_equal locations.length, LOCATION_COUNT
end
def test_programs
programs = @tester.programs
assert_kind_of Array, programs
assert_equal programs.length, PROGRAM_COUNT
end
def test_taglines
taglines = @tester.taglines
assert_kind_of Array, taglines
assert_equal taglines.length, TAGLINE_COUNT
end
def test_users
users = @tester.users
assert_kind_of Array, users
assert_equal users.length, USER_COUNT
end
def test_vehicles
vehicles = @tester.vehicles
assert_kind_of Array, vehicles
assert_equal vehicles.length, VEHICLE_COUNT
end
end
| ruby | MIT | a4d5e503edda970fc085e942018ee235622bfb11 | 2026-01-04T15:37:50.353881Z | false |
faker-ruby/faker | https://github.com/faker-ruby/faker/blob/a4d5e503edda970fc085e942018ee235622bfb11/test/faker/movies/test_faker_princess_bride.rb | test/faker/movies/test_faker_princess_bride.rb | # frozen_string_literal: true
require_relative '../../test_helper'
class TestFakerPrincessBride < Test::Unit::TestCase
def setup
@tester = Faker::Movies::PrincessBride
end
def test_character
assert_match(/\w+/, @tester.character)
end
def test_quote
assert_match(/\w+/, @tester.quote)
end
end
| ruby | MIT | a4d5e503edda970fc085e942018ee235622bfb11 | 2026-01-04T15:37:50.353881Z | false |
faker-ruby/faker | https://github.com/faker-ruby/faker/blob/a4d5e503edda970fc085e942018ee235622bfb11/test/faker/movies/test_faker_lebowski.rb | test/faker/movies/test_faker_lebowski.rb | # frozen_string_literal: true
require_relative '../../test_helper'
class TestFakerLebowski < Test::Unit::TestCase
def setup
@tester = Faker::Movies::Lebowski
end
def test_actor
assert_match(/\w+/, @tester.actor)
end
def test_character
assert_match(/\w+/, @tester.character)
end
def test_quote
assert_match(/\w+/, @tester.quote)
end
end
| ruby | MIT | a4d5e503edda970fc085e942018ee235622bfb11 | 2026-01-04T15:37:50.353881Z | false |
faker-ruby/faker | https://github.com/faker-ruby/faker/blob/a4d5e503edda970fc085e942018ee235622bfb11/test/faker/movies/test_faker_star_wars.rb | test/faker/movies/test_faker_star_wars.rb | # frozen_string_literal: true
require_relative '../../test_helper'
class TestFakerStarWars < Test::Unit::TestCase
def setup
@tester = Faker::Movies::StarWars
end
def test_call_sign
assert_match(/\w+/, @tester.call_sign)
end
def test_character
assert_match(/\w+/, @tester.character)
end
def test_droid
assert_match(/\w+/, @tester.droid)
end
def test_planet
assert_match(/\w+/, @tester.planet)
end
def test_quote
assert_match(/\w+/, @tester.quote)
end
# test good match
def test_random_character_quote
assert_match(/\w+/, @tester.quote(character: 'admiral_ackbar'))
end
# test good alternate spelling match
def test_random_character_alt_spelling_quote
assert_match(/\w+/, @tester.quote(character: 'ackbar'))
end
# test error on no match
def test_invalid_quote
assert_raise ArgumentError do
@tester.quote(character: 'Leto Atreides')
end
end
def test_specie
assert_match(/\w+/, @tester.specie)
end
def test_vehicle
assert_match(/\w+/, @tester.vehicle)
end
def test_wookiee_sentence
assert_match(/\w+/, @tester.wookiee_sentence)
end
def test_call_numbers
assert_kind_of Array, @tester.call_numbers
end
def test_call_squadrons
assert_kind_of Array, @tester.call_squadrons
end
def test_characters
assert_kind_of Array, @tester.characters
end
def test_droids
assert_kind_of Array, @tester.droids
end
def test_planets
assert_kind_of Array, @tester.planets
end
def test_species
assert_kind_of Array, @tester.species
end
def test_vehicles
assert_kind_of Array, @tester.vehicles
end
def test_wookiee_words
assert_kind_of Array, @tester.wookiee_words
end
end
| ruby | MIT | a4d5e503edda970fc085e942018ee235622bfb11 | 2026-01-04T15:37:50.353881Z | false |
faker-ruby/faker | https://github.com/faker-ruby/faker/blob/a4d5e503edda970fc085e942018ee235622bfb11/test/faker/movies/test_faker_how_to_train_your_dragon.rb | test/faker/movies/test_faker_how_to_train_your_dragon.rb | # frozen_string_literal: true
require_relative '../../test_helper'
class TestFakerHowToTrainYourDragon < Test::Unit::TestCase
def setup
@tester = Faker::Movies::HowToTrainYourDragon
end
def test_character
assert_match(/\w+/, @tester.character)
end
def test_location
assert_match(/\w+/, @tester.location)
end
def test_dragon
assert_match(/\w+/, @tester.dragon)
end
end
| ruby | MIT | a4d5e503edda970fc085e942018ee235622bfb11 | 2026-01-04T15:37:50.353881Z | false |
faker-ruby/faker | https://github.com/faker-ruby/faker/blob/a4d5e503edda970fc085e942018ee235622bfb11/test/faker/movies/test_faker_harry_potter.rb | test/faker/movies/test_faker_harry_potter.rb | # frozen_string_literal: true
require_relative '../../test_helper'
class TestFakerHarryPotter < Test::Unit::TestCase
def setup
@tester = Faker::Movies::HarryPotter
end
def test_character
assert_match(/\w+/, @tester.character)
end
def test_location
assert_match(/\w+/, @tester.location)
end
def test_quote
assert_match(/\w+/, @tester.quote)
end
def test_book
assert_match(/\w+/, @tester.book)
end
def test_house
assert_match(/\w+/, @tester.house)
end
def test_spell
assert_match(/\w+/, @tester.spell)
end
end
| ruby | MIT | a4d5e503edda970fc085e942018ee235622bfb11 | 2026-01-04T15:37:50.353881Z | false |
faker-ruby/faker | https://github.com/faker-ruby/faker/blob/a4d5e503edda970fc085e942018ee235622bfb11/test/faker/movies/test_faker_departed.rb | test/faker/movies/test_faker_departed.rb | # frozen_string_literal: true
require_relative '../../test_helper'
class TestFakerDeparted < Test::Unit::TestCase
def setup
@tester = Faker::Movies::Departed
end
def test_actor
assert_match(/\w+/, @tester.actor)
end
def test_character
assert_match(/\w+/, @tester.character)
end
def test_quote
assert_match(/\w+/, @tester.quote)
end
end
| ruby | MIT | a4d5e503edda970fc085e942018ee235622bfb11 | 2026-01-04T15:37:50.353881Z | false |
faker-ruby/faker | https://github.com/faker-ruby/faker/blob/a4d5e503edda970fc085e942018ee235622bfb11/test/faker/movies/test_faker_hobbit.rb | test/faker/movies/test_faker_hobbit.rb | # frozen_string_literal: true
require_relative '../../test_helper'
class TestFakerMoviesHobbit < Test::Unit::TestCase
def setup
@tester = Faker::Movies::Hobbit
end
def test_character
assert_match(/\w+/, @tester.character)
end
def test_quote
assert_match(/\w+/, @tester.quote)
end
def test_location
assert_match(/\w+/, @tester.location)
end
def test_thorins_company
assert_match(/\w+/, @tester.thorins_company)
end
end
| ruby | MIT | a4d5e503edda970fc085e942018ee235622bfb11 | 2026-01-04T15:37:50.353881Z | false |
faker-ruby/faker | https://github.com/faker-ruby/faker/blob/a4d5e503edda970fc085e942018ee235622bfb11/test/faker/movies/test_faker_movie.rb | test/faker/movies/test_faker_movie.rb | # frozen_string_literal: true
require_relative '../../test_helper'
class TestFakerMovie < Test::Unit::TestCase
def setup
@tester = Faker::Movie
end
def test_title
assert_match(/\w+/, @tester.title)
end
def test_quote
assert_match(/\w+/, @tester.quote)
end
end
| ruby | MIT | a4d5e503edda970fc085e942018ee235622bfb11 | 2026-01-04T15:37:50.353881Z | false |
faker-ruby/faker | https://github.com/faker-ruby/faker/blob/a4d5e503edda970fc085e942018ee235622bfb11/test/faker/movies/test_faker_avatar.rb | test/faker/movies/test_faker_avatar.rb | # frozen_string_literal: true
require_relative '../../test_helper'
class TestFakerMovieAvatar < Test::Unit::TestCase
def setup
@tester = Faker::Movies::Avatar
end
def test_character
assert_match(/\w+/, @tester.character)
end
def test_date
assert_match(/\w+/, @tester.date)
end
def test_quote
assert_match(/\w+/, @tester.quote)
end
end
| ruby | MIT | a4d5e503edda970fc085e942018ee235622bfb11 | 2026-01-04T15:37:50.353881Z | false |
faker-ruby/faker | https://github.com/faker-ruby/faker/blob/a4d5e503edda970fc085e942018ee235622bfb11/test/faker/movies/test_faker_hitchhikers_guide_to_the_galaxy.rb | test/faker/movies/test_faker_hitchhikers_guide_to_the_galaxy.rb | # frozen_string_literal: true
require_relative '../../test_helper'
class TestFakerHitchhikersGuideToTheGalaxy < Test::Unit::TestCase
def setup
@tester = Faker::Movies::HitchhikersGuideToTheGalaxy
end
def test_character
assert_match(/\w+/, @tester.character)
end
def test_location
assert_match(/\w+/, @tester.location)
end
def test_marvin_quote
assert_match(/\w+/, @tester.marvin_quote)
end
def test_planet
assert_match(/\w+/, @tester.planet)
end
def test_quote
assert_match(/\w+/, @tester.quote)
end
def test_specie
assert_match(/\w+/, @tester.specie)
end
def test_starship
assert_match(/\w+/, @tester.starship)
end
end
| ruby | MIT | a4d5e503edda970fc085e942018ee235622bfb11 | 2026-01-04T15:37:50.353881Z | false |
faker-ruby/faker | https://github.com/faker-ruby/faker/blob/a4d5e503edda970fc085e942018ee235622bfb11/test/faker/books/test_lovecraft.rb | test/faker/books/test_lovecraft.rb | # frozen_string_literal: true
require_relative '../../test_helper'
class TestFakerBooksLovecraft < Test::Unit::TestCase
def setup
@tester = Faker::Books::Lovecraft
@wordlist = I18n.translate('faker.lovecraft.words')
end
# Words delivered by this request should be on the wordlist.
def test_words
@words = @tester.words(number: 1000)
assert_equal 1000, @words.length
@words.each { |w| assert_includes @wordlist, w }
end
# Words should not return any word with spaces
def test_words_without_spaces
@words = @tester.words(number: 1000)
@words.each { |w| refute_match(/\s/, w) }
end
# Faker::Lovecraft.word generates random word from wordlist
def test_word
deterministically_verify -> { @tester.word }, depth: 5 do |word|
assert_includes @wordlist, word
end
end
# Word should not return any word with spaces
def test_word_without_spaces
deterministically_verify -> { @tester.word }, depth: 5 do |word|
refute_match(/\s/, word)
end
end
def test_exact_count_param
assert_equal(2, @tester.words(number: 2).length)
assert_equal(2, @tester.sentences(number: 2).length)
assert_equal(2, @tester.paragraphs(number: 2).length)
end
def test_range_count_param
ws = @tester.words(number: 2..5)
ss = @tester.sentences(number: 2..5)
ps = @tester.paragraphs(number: 2..5)
assert(ws.length.between?(2, 5))
assert(ss.length.between?(2, 5))
assert(ps.length.between?(2, 5))
end
def test_array_count_param
ws = @tester.words(number: [1, 4])
ss = @tester.sentences(number: [1, 4])
ps = @tester.paragraphs(number: [1, 4])
assert(ws.length == 1 || ws.length == 4)
assert(ss.length == 1 || ss.length == 4)
assert(ps.length == 1 || ps.length == 4)
end
def test_words_with_large_count_params
exact = @tester.words(number: 500)
range = @tester.words(number: 250..500)
array = @tester.words(number: [250, 500])
assert_equal(500, exact.length)
assert(range.length.between?(250, 500))
assert(array.length == 250 || array.length == 500)
end
def test_sentence_with_open_compounds_allowed
deterministically_verify -> { @tester.sentence(word_count: 5, random_words_to_add: 0, open_compounds_allowed: true) }, depth: 5 do |sentence|
assert_operator(sentence.split.length, :>=, 5)
end
end
# Sentence should not contain any open compounds
def test_sentence_without_open_compounds_allowed
deterministically_verify -> { @tester.sentence(word_count: 5, random_words_to_add: 0, open_compounds_allowed: false) }, depth: 5 do |sentence|
assert_equal(5, sentence.split.length)
end
end
def test_paragraph_char_count
paragraph = @tester.paragraph_by_chars
assert_equal(256, paragraph.length)
end
def test_tome
assert_match(/\w/, @tester.tome)
end
def test_location
assert_match(/\w/, @tester.location)
end
def test_deity
assert_match(/\w/, @tester.deity)
end
def test_fhtagn
assert_match(/\w/, @tester.fhtagn)
end
end
| ruby | MIT | a4d5e503edda970fc085e942018ee235622bfb11 | 2026-01-04T15:37:50.353881Z | false |
faker-ruby/faker | https://github.com/faker-ruby/faker/blob/a4d5e503edda970fc085e942018ee235622bfb11/test/faker/books/test_faker_culture_series.rb | test/faker/books/test_faker_culture_series.rb | # frozen_string_literal: true
require_relative '../../test_helper'
class TestFakerCultureSeries < Test::Unit::TestCase
def setup
@tester = Faker::Books::CultureSeries
end
def test_book
assert_match(/\w+/, @tester.book)
end
def test_culture_ship
assert_match(/\w+/, @tester.culture_ship)
end
def test_culture_ship_class
assert_match(/\w+/, @tester.culture_ship_class)
end
def test_culture_ship_abv
assert_match(/\w+/, @tester.culture_ship_class_abv)
end
def test_civ
assert_match(/\w+/, @tester.civ)
end
def test_planet
assert_match(/\w+/, @tester.planet)
end
end
| ruby | MIT | a4d5e503edda970fc085e942018ee235622bfb11 | 2026-01-04T15:37:50.353881Z | false |
faker-ruby/faker | https://github.com/faker-ruby/faker/blob/a4d5e503edda970fc085e942018ee235622bfb11/test/faker/books/test_book.rb | test/faker/books/test_book.rb | # frozen_string_literal: true
require_relative '../../test_helper'
class TestFakerBook < Test::Unit::TestCase
def setup
@tester = Faker::Book
end
def test_title
assert_match(/(\w+\.? ?){2,3}/, @tester.title)
end
def test_author
assert_match(/(\w+\.? ?){2,3}/, @tester.author)
end
def test_publisher
assert_match(/(\w+\.? ?){2,3}/, @tester.publisher)
end
def test_genre
assert_match(/(\w+\.? ?){2,3}/, @tester.genre)
end
end
| ruby | MIT | a4d5e503edda970fc085e942018ee235622bfb11 | 2026-01-04T15:37:50.353881Z | false |
faker-ruby/faker | https://github.com/faker-ruby/faker/blob/a4d5e503edda970fc085e942018ee235622bfb11/test/faker/books/test_the_kingkiller_chronicle.rb | test/faker/books/test_the_kingkiller_chronicle.rb | # frozen_string_literal: true
require_relative '../../test_helper'
class TestTheKingkillerChronicle < Test::Unit::TestCase
def setup
@tester = Faker::Books::TheKingkillerChronicle
end
def test_book
assert_match(/\w+/, @tester.book)
end
def test_character
assert_match(/\w+/, @tester.character)
end
def test_creature
assert_match(/\w+/, @tester.creature)
end
def test_location
assert_match(/\w+/, @tester.location)
end
end
| ruby | MIT | a4d5e503edda970fc085e942018ee235622bfb11 | 2026-01-04T15:37:50.353881Z | false |
faker-ruby/faker | https://github.com/faker-ruby/faker/blob/a4d5e503edda970fc085e942018ee235622bfb11/test/faker/books/test_dune.rb | test/faker/books/test_dune.rb | # frozen_string_literal: true
require_relative '../../test_helper'
class TestFakerBooksDune < Test::Unit::TestCase
def setup
@tester = Faker::Books::Dune
end
def test_character
assert_match(/\w+/, @tester.character)
end
def test_title
assert_match(/\w+/, @tester.title)
end
def test_planet
assert_match(/\w+/, @tester.planet)
end
def test_city
assert_match(/\w+/, @tester.city)
end
def test_quote
assert_match(/\w+/, @tester.quote)
end
def test_saying
assert_match(/\w+/, @tester.saying)
end
end
| ruby | MIT | a4d5e503edda970fc085e942018ee235622bfb11 | 2026-01-04T15:37:50.353881Z | false |
faker-ruby/faker | https://github.com/faker-ruby/faker/blob/a4d5e503edda970fc085e942018ee235622bfb11/test/faker/books/test_faker_dune.rb | test/faker/books/test_faker_dune.rb | # frozen_string_literal: true
require_relative '../../test_helper'
class TestFakerDune < Test::Unit::TestCase
def setup
@tester = Faker::Books::Dune
end
def test_character
assert_match(/\w+/, @tester.character)
end
def test_title
assert_match(/\w+/, @tester.title)
end
def test_city
assert_match(/\w+/, @tester.city)
end
def test_planet
assert_match(/\w+/, @tester.planet)
end
def test_random_quote
assert_match(/\w+/, @tester.quote)
end
# test good match
def test_random_character_quote
assert_match(/\w+/, @tester.quote(character: 'paul'))
end
# test error on no match
def test_invalid_quote
assert_raise ArgumentError do
@tester.quote(character: 'Luke Skywalker')
end
end
def test_random_saying
assert_match(/\w+/, @tester.saying)
end
# test good match
def test_random_source_saying
assert_match(/\w+/, @tester.saying(source: 'fremen'))
end
# test error on no match
def test_invalid_saying
assert_raise ArgumentError do
@tester.saying(source: 'Ewoks')
end
end
end
| ruby | MIT | a4d5e503edda970fc085e942018ee235622bfb11 | 2026-01-04T15:37:50.353881Z | false |
faker-ruby/faker | https://github.com/faker-ruby/faker/blob/a4d5e503edda970fc085e942018ee235622bfb11/lib/faker.rb | lib/faker.rb | # frozen_string_literal: true
mydir = __dir__
require 'psych'
require 'i18n'
Dir.glob(File.join(mydir, 'helpers', '*.rb')).each { |file| require file }
I18n.load_path += Dir[File.join(mydir, 'locales', '**/*.yml')]
module Faker
module Config
@default_locale = nil
class << self
attr_writer :default_locale
def locale=(new_locale)
Thread.current[:faker_config_locale] = new_locale
end
def locale
# Because I18n.locale defaults to :en, if we don't have :en in our available_locales, errors will happen
Thread.current[:faker_config_locale] || @default_locale || (I18n.available_locales.include?(I18n.locale) ? I18n.locale : I18n.available_locales.first)
end
def own_locale
Thread.current[:faker_config_locale]
end
def random=(new_random)
Thread.current[:faker_config_random] = new_random
end
def random
Thread.current[:faker_config_random] || Random
end
end
end
class Base
Numbers = Array(0..9)
ULetters = Array('A'..'Z')
LLetters = Array('a'..'z')
Letters = ULetters + LLetters
class << self
attr_reader :flexible_key
NOT_GIVEN = Object.new
## by default numerify results do not start with a zero
def numerify(number_string, leading_zero: false)
return number_string.gsub('#') { rand(10).to_s } if leading_zero
number_string.sub('#') { rand(1..9).to_s }.gsub('#') { rand(10).to_s }
end
def letterify(letter_string)
letter_string.gsub('?') { sample(ULetters) }
end
def bothify(string)
letterify(numerify(string))
end
def generate(as_type, &block)
PositionalGenerator.new(as_type, &block).generate
end
# Given a regular expression, attempt to generate a string
# that would match it. This is a rather simple implementation,
# so don't be shocked if it blows up on you in a spectacular fashion.
#
# It does not handle ., *, unbounded ranges such as {1,},
# extensions such as (?=), character classes, some abbreviations
# for character classes, and nested parentheses.
#
# I told you it was simple. :) It's also probably dog-slow,
# so you shouldn't use it.
#
# It will take a regex like this:
#
# /^[A-PR-UWYZ0-9][A-HK-Y0-9][AEHMNPRTVXY0-9]?[ABEHMNPRVWXY0-9]? {1,2}[0-9][ABD-HJLN-UW-Z]{2}$/
#
# and generate a string like this:
#
# "U3V 3TP"
#
def regexify(reg)
reg = reg.source if reg.respond_to?(:source) # Handle either a Regexp or a String that looks like a Regexp
reg
.gsub(%r{^/?\^?}, '').gsub(%r{\$?/?$}, '') # Ditch the anchors
.gsub(/\{(\d+)\}/, '{\1,\1}').gsub('?', '{0,1}') # All {2} become {2,2} and ? become {0,1}
.gsub(/(\[[^\]]+\])\{(\d+),(\d+)\}/) { |_match| Regexp.last_match(1) * sample(Array(Range.new(Regexp.last_match(2).to_i, Regexp.last_match(3).to_i))) } # [12]{1,2} becomes [12] or [12][12]
.gsub(/(\([^)]+\))\{(\d+),(\d+)\}/) { |_match| Regexp.last_match(1) * sample(Array(Range.new(Regexp.last_match(2).to_i, Regexp.last_match(3).to_i))) } # (12|34){1,2} becomes (12|34) or (12|34)(12|34)
.gsub(/(\\?.)\{(\d+),(\d+)\}/) { |_match| Regexp.last_match(1) * sample(Array(Range.new(Regexp.last_match(2).to_i, Regexp.last_match(3).to_i))) } # A{1,2} becomes A or AA or \d{3} becomes \d\d\d
.gsub(/\((.*?)\)/) { |match| sample(match.gsub(/[()]/, '').split('|')) } # (this|that) becomes 'this' or 'that'
.gsub(/\[([^\]]+)\]/) { |match| match.gsub(/(\w-\w)/) { |range| sample(Array(Range.new(*range.split('-')))) } } # All A-Z inside of [] become C (or X, or whatever)
.gsub(/\[([^\]]+)\]/) { |_match| sample(Regexp.last_match(1).chars) } # All [ABC] become B (or A or C)
.gsub('\d') { |_match| sample(Numbers) }
.gsub('\w') { |_match| sample(Letters) }
end
# Helper for the common approach of grabbing a translation
# with an array of values and selecting one of them.
def fetch(key)
fetched = sample(translate("faker.#{key}"))
if fetched&.match(%r{^/}) && fetched.match(%r{/$}) # A regex
regexify(fetched)
else
fetched
end
end
# Helper for the common approach of grabbing a translation
# with an array of values and returning all of them.
def fetch_all(key)
fetched = translate("faker.#{key}")
fetched = fetched.last if fetched.size <= 1
if !fetched.respond_to?(:sample) && fetched.match(%r{^/}) && fetched.match(%r{/$}) # A regex
regexify(fetched)
else
fetched
end
end
# 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}".
def parse(key)
fetched = fetch(key)
parts = fetched.scan(/(\(?)#\{([A-Za-z]+\.)?([^}]+)\}([^#]+)?/).map do |prefix, kls, meth, etc|
# If the token had a class Prefix (e.g., Name.first_name)
# grab the constant, otherwise use self
cls = kls ? Faker.const_get(kls.chop) : self
# If an optional leading parentheses is not present, prefix.should == "", otherwise prefix.should == "("
# In either case the information will be retained for reconstruction of the string.
text = prefix
# If the class has the method, call it, otherwise fetch the translation
# (e.g., faker.phone_number.area_code)
text += if cls.respond_to?(meth)
cls.send(meth)
else
# Do just enough snake casing to convert PhoneNumber to phone_number
key_path = cls.to_s.split('::').last.gsub(/([a-z\d])([A-Z])/, '\1_\2').downcase
fetch("#{key_path}.#{meth.downcase}")
end
# And tack on spaces, commas, etc. left over in the string
text + etc.to_s
end
# If the fetched key couldn't be parsed, then fallback to numerify
parts.any? ? parts.join : numerify(fetched)
end
# Call I18n.translate with our configured locale if no
# locale is specified
def translate(*args, **opts)
opts[:locale] ||= Faker::Config.locale
opts[:raise] = true
I18n.translate(*args, **opts)
rescue I18n::MissingTranslationData
opts[:locale] = :en
# Super-simple fallback -- fallback to en if the
# translation was missing. If the translation isn't
# in en either, then it will raise again.
disable_enforce_available_locales do
I18n.translate(*args, **opts)
end
end
# Executes block with given locale set.
def with_locale(tmp_locale = nil, &block)
current_locale = Faker::Config.own_locale
Faker::Config.locale = tmp_locale
disable_enforce_available_locales do
I18n.with_locale(tmp_locale, &block)
end
ensure
Faker::Config.locale = current_locale
end
def flexible(key)
@flexible_key = key
end
# 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
def method_missing(mth, *args, &block)
super unless flexible_key
if (translation = translate("faker.#{flexible_key}.#{mth}"))
sample(translation)
else
super
end
end
def respond_to_missing?(method_name, include_private = false)
super
end
# Generates a random value between the interval
def rand_in_range(from, to)
from, to = to, from if to < from
rand(from..to)
end
# If an array or range is passed, a random value will be selected.
# All other values are simply returned.
def resolve(value)
case value
when Array then sample(value)
when Range then rand value
else value
end
end
# Return unique values from the generator every time.
#
# @param max_retries [Integer] The max number of retries that should be done before giving up.
# @return [self]
def unique(max_retries = 10_000)
@unique ||= UniqueGenerator.new(self, max_retries)
end
def sample(list, num = nil)
if list.respond_to?(:sample)
if num
list.sample(num, random: Faker::Config.random)
else
list.sample(random: Faker::Config.random)
end
else
list
end
end
def shuffle(list)
list.shuffle(random: Faker::Config.random)
end
def shuffle!(list)
list.shuffle!(random: Faker::Config.random)
end
def rand(max = nil)
if max.nil?
Faker::Config.random.rand
elsif max.is_a?(Range) || max.to_i.positive?
Faker::Config.random.rand(max)
else
0
end
end
def disable_enforce_available_locales
old_enforce_available_locales = I18n.enforce_available_locales
I18n.enforce_available_locales = false
yield
ensure
I18n.enforce_available_locales = old_enforce_available_locales
end
end
end
end
# require faker objects
Dir.glob(File.join(mydir, 'faker', '/**/*.rb')).each { |file| require file }
| ruby | MIT | a4d5e503edda970fc085e942018ee235622bfb11 | 2026-01-04T15:37:50.353881Z | false |
faker-ruby/faker | https://github.com/faker-ruby/faker/blob/a4d5e503edda970fc085e942018ee235622bfb11/lib/helpers/char.rb | lib/helpers/char.rb | # frozen_string_literal: true
module Faker
module Char
def self.prepare(string)
result = romanize_cyrillic string
result = fix_umlauts result
result.gsub(/[^\w-]/, '').downcase
end
def self.fix_umlauts(string)
string.gsub(/[äöüß]/i) do |match|
case match.downcase
when 'ä' then 'ae'
when 'ö' then 'oe'
when 'ü' then 'ue'
when 'ß' then 'ss'
else match.downcase
end
end
end
def self.romanize_cyrillic(string)
if Faker::Config.locale == 'uk'
# Based on conventions abopted by BGN/PCGN for Ukrainian
uk_chars = {
'а' => 'a', 'б' => 'b', 'в' => 'v', 'г' => 'h', 'ґ' => 'g', 'д' => 'd', 'е' => 'e',
'є' => 'ye', 'ж' => 'zh', 'з' => 'z', 'и' => 'y', 'і' => 'i', 'ї' => 'yi', 'й' => 'y',
'к' => 'k', 'л' => 'l', 'м' => 'm', 'н' => 'n', 'о' => 'o', 'п' => 'p', 'р' => 'r',
'с' => 's', 'т' => 't', 'у' => 'u', 'ф' => 'f', 'х' => 'kh', 'ц' => 'ts', 'ч' => 'ch',
'ш' => 'sh', 'щ' => 'shch', 'ю' => 'yu', 'я' => 'ya', 'А' => 'a', 'Б' => 'b', 'В' => 'v',
'Г' => 'h', 'Ґ' => 'g', 'Д' => 'd', 'Е' => 'e', 'Є' => 'ye', 'Ж' => 'zh', 'З' => 'z',
'И' => 'y', 'І' => 'i', 'Ї' => 'yi', 'Й' => 'y', 'К' => 'k', 'Л' => 'l', 'М' => 'm',
'Н' => 'n', 'О' => 'o', 'П' => 'p', 'Р' => 'r', 'С' => 's', 'Т' => 't', 'У' => 'u',
'Ф' => 'f', 'Х' => 'kh', 'Ц' => 'ts', 'Ч' => 'ch', 'Ш' => 'sh', 'Щ' => 'shch', 'Ю' => 'yu',
'Я' => 'ya', 'ь' => '' # Ignore symbol, because its standard presentation is not allowed in URLs
}
return string.gsub(/[а-яА-ЯіїєґІЇЄҐ]/, uk_chars)
end
if Faker::Config.locale == 'ru'
# Based on conventions abopted by BGN/PCGN for Russian
ru_chars = {
'а' => 'a', 'б' => 'b', 'в' => 'v', 'г' => 'h', 'д' => 'd', 'е' => 'e',
'ё' => 'ye', 'ж' => 'zh', 'з' => 'z', 'и' => 'i', 'й' => 'y', 'к' => 'k',
'л' => 'l', 'м' => 'm', 'н' => 'n', 'о' => 'o', 'п' => 'p', 'р' => 'r',
'с' => 's', 'т' => 't', 'у' => 'u', 'ф' => 'f', 'х' => 'kh', 'ц' => 'ts',
'ч' => 'ch', 'ш' => 'sh', 'щ' => 'shch', 'ы' => 'у', 'э' => 'e', 'ю' => 'yu',
'я' => 'ya', 'А' => 'a', 'Б' => 'b', 'В' => 'v', 'Г' => 'h', 'Д' => 'd',
'Е' => 'e', 'Ё' => 'ye', 'Ж' => 'zh', 'З' => 'z', 'И' => 'i', 'Й' => 'y',
'К' => 'k', 'Л' => 'l', 'М' => 'm', 'Н' => 'n', 'О' => 'o', 'П' => 'p', 'Р' => 'r',
'С' => 's', 'Т' => 't', 'У' => 'u', 'Ф' => 'f', 'Х' => 'kh', 'Ц' => 'ts',
'Ч' => 'ch', 'Ш' => 'sh', 'Щ' => 'shch', 'Ы' => 'у', 'Э' => 'e', 'Ю' => 'yu',
'Я' => 'ya', 'ь' => '', 'ъ' => '' # Ignore symbols, because its standard presentation is not allowed in URLs
}
return string.gsub(/[а-яА-Я]/, ru_chars)
end
string
end
end
end
| ruby | MIT | a4d5e503edda970fc085e942018ee235622bfb11 | 2026-01-04T15:37:50.353881Z | false |
faker-ruby/faker | https://github.com/faker-ruby/faker/blob/a4d5e503edda970fc085e942018ee235622bfb11/lib/helpers/unique_generator.rb | lib/helpers/unique_generator.rb | # frozen_string_literal: true
module Faker
class UniqueGenerator
def initialize(generator, max_retries)
@generator = generator
@max_retries = max_retries
end
def method_missing(name, *arguments)
self.class.marked_unique.add(self)
@max_retries.times do
result = @generator.public_send(name, *arguments)
next if previous_results[[name, arguments]].include?(result)
previous_results[[name, arguments]] << result
return result
end
raise RetryLimitExceeded, "Retry limit exceeded for #{name}"
end
# Have method_missing use ruby 2.x keywords if the method exists.
# This is necessary because the syntax for passing arguments (`...`)
# is invalid on versions before Ruby 2.7, so it can't be used.
ruby2_keywords(:method_missing) if respond_to?(:ruby2_keywords, true)
def respond_to_missing?(method_name, include_private = false)
method_name.to_s.start_with?('faker_') || super
end
RetryLimitExceeded = Class.new(StandardError)
def previous_results
Thread.current[:faker_unique_generator_previous_results] ||= {}
Thread.current[:faker_unique_generator_previous_results][@generator] ||= Hash.new { |hash, key| hash[key] = Set.new }
end
def clear
previous_results.clear
end
def self.marked_unique
Thread.current[:faker_unique_generator_marked_unique] ||= Set.new
end
def self.clear
marked_unique.each(&:clear)
marked_unique.clear
end
def exclude(name, arguments, values)
values ||= []
values.each do |value|
previous_results[[name, arguments]] << value
end
end
end
end
| ruby | MIT | a4d5e503edda970fc085e942018ee235622bfb11 | 2026-01-04T15:37:50.353881Z | false |
faker-ruby/faker | https://github.com/faker-ruby/faker/blob/a4d5e503edda970fc085e942018ee235622bfb11/lib/helpers/positional_generator.rb | lib/helpers/positional_generator.rb | # frozen_string_literal: true
##
# A high level way to generate a list of generated values that fit a specific
# format, such as an ID, postal code, or phone number.
#
# It provides generators for random digits and letters, hardcoded literal
# strings, computed values based on previously-generated values, union (one-of)
# selectors, and grouped generators.
#
# The generation allows for dependencies on previously generated values -- most
# useful for computations -- and this object knows how to build that dependency
# graph.
#
# See {PositionalGenerator::Builder} for more.
class PositionalGenerator
##
# @param as_type [Symbol] +:string+ to generate a String
# @param block [Method] a function that interacts with the {Builder}
def initialize(as_type, &block)
@block = block
@generator_builder = Builder.new(as_type)
end
##
# @return [String] if +as_type+ is +:string+
def generate
@block.call(@generator_builder)
@generator_builder.build
end
Component = Struct.new(:position, :name, :deps, :generator)
class Builder
attr_reader :as_type
def initialize(as_type)
@components = []
@as_type = as_type
end
##
# Generate a value in the range of 0..9.
#
# @param name [Symbol] the name for this node in the group
# @param length [Integer] how many digits to generate
# @param ranges [Array<Range, Array, Set>] an array of limitations on the
# generation. Elements can be a Range to select from within that range,
# or an Array or Set to select an element from within the list.
# @return [void]
#
# @example a digit
# int
#
# @example five digits named :a
# int(name: :a, length: 5)
#
# @example digits of any length between 4 to 10
# int(ranges: [1_000 .. 9_999_999_999)
def int(name: nil, length: 1, ranges: nil)
@components << Component.new(@components.count, name, [], Int.new(length, ranges))
end
##
# Generate a value in the range of 'a'..'Z'.
#
# @param name [Symbol] the name for this node in the group
# @param length [Integer, Range] how many letters to generate
# @param ranges [Array<Range, Array, Set>] an array of limitations on the
# generation. Elements can be a Range to select from within that range,
# or an Array or Set to select an element from within the list.
# @return [void]
#
# @example Generate a letter
# letter
#
# @example Generate five uppercase letters named :b
# letter(name: :b, length: 5, ranges: ['A'..'Z'])
#
# @example Generate three-letter strings from within specific values
# letter(ranges: ['700'..'799', '7A0'..'7F9'])
def letter(name: nil, length: 1, ranges: ['a'..'z', 'A'..'Z'])
@components << Component.new(@components.count, name, [], Letter.new(length, ranges))
end
##
# Generate a literal String
#
# @param value [String]
# @param name [Symbol] the name for this node in the group
# @return [void]
# @example
# lit("-")
def lit(value, name: nil)
@components << Component.new(@components.count, name, [], Literal.new(value))
end
##
# Fill the position with an arbitrary value.
#
# @param name [Symbol] the name for this node in the group
# @param deps [Array<Symbol>] the name of other fields that this one depends on
# @param block [Method] the block that yields the arbitrary value. Its
# arguments are the deps.
# @return [void]
#
# @example Today's date
# computed do
# Date.today
# end
#
# @example A check digit
# int(name: :a, length: 5)
# computed(deps: [:a]) do |a|
# a.to_s.bytes.sum % 10
# end
def computed(name: nil, deps: [], &block)
@components << Component.new(@components.count, name, deps, Computed.new(block))
end
##
# Fill the position with one of the results from the given generators.
#
# @param name [Symbol] the name for this node in the group
# @param block [Method] subgenerator block
# @return [void]
#
# @example Either five digits, or two letters
# oneof do |or_else|
# or_else.int(length: 5)
# or_else.letter(length: 2)
# end
#
# @example Either one letter; or a slash, five digits, then a slash.
# oneof do |or_else|
# or_else.letter
# or_else.group do |g_|
# g_.lit("/")
# g_.digit(length: 5)
# g_.lit("/")
# end
# end
def oneof(name: nil, &block)
@components << Component.new(@components.count, name, [], Oneof.new(self, block))
end
##
# A group of generators. Useful for {#oneof}.
#
# @param name [Symbol] the name for this node in the group
# @param block [Method] a subgenerator block
# @return [void]
def group(name: nil, &block)
@components << Component.new(@components.count, name, [], Group.new(@as_type, block))
end
##
# Generate the value.
#
# @return [String] if +as_type+ is +:string+
def build
graph = build_graph
stack = build_stack(graph)
values = generate_values(stack)
convert(values)
end
private
##
# Turn the components into a graph following dependencies.
#
# @return [Array<(Integer, Integer)>]
#
# Components can have dependencies. Here's one where a computation (b)
# depends on a value generated after it (c):
#
# @components = [
# Int.new(0, :a, 1, nil),
# Computed.new(1, :b, [:c]) { |c| c + 1 },
# Int.new(2, :c, 1, nil),
# ]
#
# We can think of a graph like so:
#
# (a) (c)
# | |
# | (b)
# \ /
# end
#
# Or in Mermaid:
#
# ```mermaid
# stateDiagram-v2
# a --> [*]
# c --> b
# b --> [*]
# ```
#
# This method builds that graph, using their positional locations as the
# ID. The end state is represented as +nil+. So continuing the example
# above, it will give this output:
#
# [
# [0, nil],
# [2, 1],
# [1, nil],
# ]
#
# Later we can look up the appropriate component by indexing into the
# +@components+ array.
def build_graph
graph = []
# rubocop:disable Style/CombinableLoops
@components.each do |component|
component.deps.each do |dep|
dep_component = @components.detect { |c| c.name == dep }
raise if dep_component.nil?
graph.push([dep_component.position, component.position])
end
end
@components.each do |component|
graph.push([component.position, nil]) if graph.none? { |(from, _to)| from == component.position }
end
# rubocop:enable Style/CombinableLoops
graph
end
##
# Produce a stack of components to evaluate in sequence.
#
# @param graph [Array<(Integer, Integer)>]
# @return [Array<Array<Int>>]
#
# Now that we have a graph, we know enough to determine how to traverse the
# generators such that all dependencies are met.
#
# The initial stack is an array of all the free traversals to the goal
# (where the +to+ is +nil+).
#
# Loop over the top of the stack:
# - The next array is all the nodes that lead into the nodes atop the
# stack.
# - If the next array has values, push that onto the top of the stack.
# - If the next array is empty, we are done.
#
# For example, given the graph:
#
# [
# [0, nil],
# [2, 1],
# [1, nil],
# ]
#
# The initial stack is:
#
# [
# [0, 1]
# ]
#
# We loop over the top of the stack, +[0, 1]+, and find all the nodes of
# the graph that lead there. Nothing leads to +0+, and +2+ leads to +1+.
#
# Therefore, push +[2]+ to the top of the stack.
#
# Repeat for +[2]+. Nothing leads to +2+, so our new goal is +[]+. This is
# empty, so don't push it onto the stack. We are done.
#
# The final stack is:
#
# [
# [0, 1],
# [2]
# ]
def build_stack(graph)
require 'set'
terminals = graph.filter_map { |(from, to)| to.nil? && from }
stack = [terminals]
seen = Set.new(terminals)
deps = []
loop do
stack[-1].each do |e|
deps = graph.select { |(from, to)| to == e && !seen.include?(from) }.map do |from, _to|
seen << from
from
end
stack << deps if deps.any?
end
break if deps.empty?
end
stack
end
##
# Turn a stack into a list of generated values.
#
# @param stack [Array<Array<Int>>]
# @return [Array<Object>] values sorted by desired order
#
# We start with a stack of components we need evaluated. We have been
# tracking these components by position, so first we need to look up the
# component in our list.
#
# From there we can get a list of all the dependencies for the component.
# These have already been evaluated, since +stack+ is sorted, so we fetch
# them.
#
# Since the stack was sorted by computation order, we must re-sort them
# into positional order at the end.
def generate_values(stack)
result = []
while (top = stack.pop)
top.each do |component_id|
component = @components[component_id]
raise if component.nil?
values = result.filter_map do |(_id, name, value)|
value if component.deps.include?(name)
end
result << [component.position, component.name, component.generator.generate(values)]
end
end
result.sort_by do |component_position, _, _|
component_position
end
end
##
# @param values [Array<Object>]
# @return [String] if +@as_type+ is +:string+
# @raise [ArgumentError] if +@as_type+ is unsupported
def convert(values)
case @as_type
when :string
values.inject('') do |acc, (_, _, v)|
"#{acc}#{v}"
end
else
raise ArgumentError, "unknown return type: #{@as_type}"
end
end
class Group
def initialize(as_type, block)
@as_type = as_type
@block = block
end
def generate(_)
builder = Builder.new(@as_type)
@block.call(builder)
builder.build
end
end
class Oneof
def initialize(builder, block)
@block = block
@builder = builder
end
def generate(...)
subgens = OneofSelector.new(@builder)
@block.call(subgens)
subgens.sample
subgens.generate(...)
end
class OneofSelector
def initialize(builder)
@subgens = []
@builder = Builder.new(builder.as_type)
end
def method_missing(meth, *args, **kwargs, &block)
@subgens << [meth, args, kwargs, block]
end
def respond_to_missing?(method_name, include_private = false)
@builder.respond_to?(method_name, include_private)
end
def sample
(meth, args, kwargs, block) = Faker::Base.sample(@subgens)
@builder.send(meth, *args, **kwargs, &block)
end
def generate(...)
@builder.build
end
end
end
class Int
def initialize(length, ranges)
# Internally we store only an Enumerable of Range values. So if we are
# not given any Ranges but are given a length, we need to convert the
# length to a Range.
#
# If the length is `5`, that means we should compute the Range `10000..99999`.
# We can compute the lower end with a simple exponent: 10^4 = 10000.
# The upper end is one less than an exponent: 10^5 - 1 = 99999.
if ranges.nil?
lower = 10**(length - 1)
upper = (10**length) - 1
ranges = [lower..upper]
end
@ranges = ranges
end
def generate(_)
Faker::Base.rand(@ranges.sample(random: Faker::Config.random))
end
end
class Letter
def initialize(length, ranges)
@length = length
@ranges = ranges
end
def generate(_)
@length.times.inject('') do |acc, _index|
generated_character = char
"#{acc}#{generated_character}"
end
end
private
def char
if @ranges
case s = @ranges.sample(random: Faker::Config.random)
when Range
s.to_a.sample(random: Faker::Config.random)
when Array, Set
s.sample(random: Faker::Config.random)
else
raise ArgumentError, "unsupported range type: #{s.inspect}"
end
else
Faker::Base.sample(Faker::Base::Letters)
end
end
end
class Literal
def initialize(value)
@value = value
end
def generate(_)
@value
end
end
class Computed
def initialize(block)
@block = block
end
def generate(args)
@block.call(*args)
end
end
end
end
| ruby | MIT | a4d5e503edda970fc085e942018ee235622bfb11 | 2026-01-04T15:37:50.353881Z | false |
faker-ruby/faker | https://github.com/faker-ruby/faker/blob/a4d5e503edda970fc085e942018ee235622bfb11/lib/helpers/deprecator.rb | lib/helpers/deprecator.rb | # frozen_string_literal: true
# Based on Rails ActiveSupport Deprecator
# https://github.com/rails/rails/blob/main/activesupport/lib/active_support/deprecation/constant_accessor.rb
# rubocop:disable Style/ClassVars
module Faker
# Provides a way to rename generators, including their namespaces, with a deprecation cycle in which
# both the old and new names work, but using the old one prints a deprecation message.
#
# Deprecator provides a deprecate_generator method to be used when
# renaming a generator. For example, let's say we want to change the following Generator's
# name to <tt>Faker::NewGenerator</tt>:
#
# module Faker
# class Generator
# def self.generate
# "be kind"
# end
# end
# end
#
# To rename it, you need to do the update the name and declare the deprecation by
# including the <tt>Deprecator</tt> module and using the deprecate_generator method:
#
# module Faker
# class NewGenerator
# def self.generate
# "be kind"
# end
# end
#
# include Deprecator
# deprecate_generator('DeprecatedGenerator', NewGenerator)
# end
#
# The first argument is a constant name (no colons) as a string. It is the name of
# the constant you want to deprecate.
#
# The second argument is the constant path of the replacement (no colons) as a constant.
#
# For this to work, a +const_missing+ hook is installed. When users
# reference the deprecated constant, the callback prints the
# message and constantizes the replacement.
#
# With that in place, references to <tt>Faker::Deprecator</tt> still work, they
# evaluate to <tt>Faker::NewGenerator</tt> now, and trigger a deprecation warning:
#
# Faker::Generator.generate
# # DEPRECATION WARNING: Faker::Generator is deprecated. Use Faker::NewGenerator instead
# # "be kind"
#
# For testing the deprecations, we provide <tt>assert_deprecated</tt>
# and <tt>assert_not_deprecated</tt> matchers.
#
# There's also a <tt>Faker::Deprecator.skip_warning</tt> helper to silence
# the deprecation messages in the *test* output. Use it for generators that have lots of tests
# to avoid too many noise when running the tests.
module Deprecator
def self.included(base)
extension = Module.new do
def const_missing(missing_const_name)
if class_variable_defined?(:@@_deprecated_constants) && (replacement = class_variable_get(:@@_deprecated_constants)[missing_const_name.to_s])
unless Faker::Deprecator.skip_warning?
deprecated_message = "#{name}::#{replacement[:old_generator]} is deprecated."
replacement_message = "Use #{replacement[:new_constant]} instead."
$stdout.puts("DEPRECATION WARNING: #{deprecated_message} #{replacement_message}")
end
return replacement[:new_constant]
end
super
end
def deprecate_generator(old_generator_name, new_generator_constant)
class_variable_set(:@@_deprecated_constants, {}) unless class_variable_defined?(:@@_deprecated_constants)
class_variable_get(:@@_deprecated_constants)[old_generator_name] = {
new_constant: new_generator_constant,
old_generator: old_generator_name
}
end
end
base.singleton_class.prepend extension
end
# Silence deprecation warnings within the block.
#
# Faker::Generator.generate
# # => DEPRECATION WARNING: Faker::Generator is deprecated. Use Faker::NewGenerator instead.
#
# Faker::Deprecator.skip_warning do
# Faker::Generator.generate
# end
# # => nil
def self.skip_warning
original = Faker::Deprecator.skip
Faker::Deprecator.skip = true
yield
ensure
Faker::Deprecator.skip = original
end
def self.skip_warning?
@skip == true
end
def self.skip
@skip ||= false
end
def self.skip=(value)
@skip = value
end
end
end
# rubocop:enable Style/ClassVars
| ruby | MIT | a4d5e503edda970fc085e942018ee235622bfb11 | 2026-01-04T15:37:50.353881Z | false |
faker-ruby/faker | https://github.com/faker-ruby/faker/blob/a4d5e503edda970fc085e942018ee235622bfb11/lib/helpers/base58.rb | lib/helpers/base58.rb | # frozen_string_literal: true
module Faker
module Base58
def self.encode(str)
alphabet = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
base = alphabet.size
lv = 0
str.chars.reverse.each_with_index { |v, i| lv += v.unpack1('C') * 256**i }
ret = +''
while lv.positive?
lv, mod = lv.divmod(base)
ret << alphabet[mod]
end
npad = str.match(/^#{0.chr}*/)[0].to_s.size
'1' * npad + ret.reverse
end
end
end
| ruby | MIT | a4d5e503edda970fc085e942018ee235622bfb11 | 2026-01-04T15:37:50.353881Z | false |
faker-ruby/faker | https://github.com/faker-ruby/faker/blob/a4d5e503edda970fc085e942018ee235622bfb11/lib/faker/version.rb | lib/faker/version.rb | # frozen_string_literal: true
module Faker # :nodoc:
VERSION = '3.5.3'
end
| ruby | MIT | a4d5e503edda970fc085e942018ee235622bfb11 | 2026-01-04T15:37:50.353881Z | false |
faker-ruby/faker | https://github.com/faker-ruby/faker/blob/a4d5e503edda970fc085e942018ee235622bfb11/lib/faker/blockchain/aeternity.rb | lib/faker/blockchain/aeternity.rb | # frozen_string_literal: true
module Faker
class Blockchain
class Aeternity < Base
class << self
##
# Produces a random Aeternity wallet address
#
# @return [String]
#
# @example
# Faker::Blockchain::Aeternity.address
# #=> "ak_zvU8YQLagjcfng7Tg8yCdiZ1rpiWNp1PBn3vtUs44utSvbJVR"
#
def address
"ak_#{rand_strings}"
end
##
# Produces a random Aeternity transaction
#
# @return [String]
#
# @example
# Faker::Blockchain::Aeternity.transaction
# #=> "th_147nDP22h3pHrLt2qykTH4txUwQh1ccaXp"
#
def transaction
"th_#{rand_strings(51)}"
end
##
# Produces a random Aeternity contract
#
# @return [String]
#
# @example
# Faker::Blockchain::Aeternity.contract
# #=> "ct_Hk2JsNeWGEYQEHHQCfcBeGrwbhtYSwFTPdDhW2SvjFYVojyhW"
#
def contract
"ct_#{rand_strings}"
end
##
# Produces a random Aeternity oracle
#
# @return [String]
#
# @example
# Faker::Blockchain::Aeternity.oracle
# #=> "ok_28QDg7fkF5qiKueSdUvUBtCYPJdmMEoS73CztzXCRAwMGKHKZh"
#
def oracle
"ok_#{rand_strings(51)}"
end
protected
def rand_strings(length = 50)
hex_alphabet = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
var = +''
length.times { var << sample(shuffle(hex_alphabet.chars)) }
var
end
end
end
end
end
| ruby | MIT | a4d5e503edda970fc085e942018ee235622bfb11 | 2026-01-04T15:37:50.353881Z | false |
faker-ruby/faker | https://github.com/faker-ruby/faker/blob/a4d5e503edda970fc085e942018ee235622bfb11/lib/faker/blockchain/bitcoin.rb | lib/faker/blockchain/bitcoin.rb | # frozen_string_literal: true
require 'openssl'
require 'securerandom'
module Faker
class Blockchain
class Bitcoin < Base
class << self
# @private
PROTOCOL_VERSIONS = {
main: 0,
testnet: 111
}.freeze
##
# Produces a Bitcoin wallet address
#
# @return [String]
#
# @example
# Faker::Blockchain::Bitcoin.address
# #=> "147nDP22h3pHrLt2qykTH4txUwQh1ccaXp"
#
# @faker.version 1.9.2
def address
address_for(:main)
end
##
# Produces a Bitcoin testnet address
#
# @return [String]
#
# @example
# Faker::Blockchain::Bitcoin.testnet_address
# #=> "n4YjRyYD6V6zREpk6opqESDqD3KYnMdVEB"
#
# @faker.version 1.9.2
def testnet_address
address_for(:testnet)
end
protected
##
# Generates a random Bitcoin address for the given network
#
# @param network [Symbol] The name of network protocol to generate an address for
# @return [String] A Bitcoin address
def address_for(network)
version = PROTOCOL_VERSIONS.fetch(network)
packed = version.chr + Faker::Config.random.bytes(20)
checksum = OpenSSL::Digest::SHA256.digest(OpenSSL::Digest::SHA256.digest(packed))[0..3]
Faker::Base58.encode(packed + checksum)
end
end
end
end
end
| ruby | MIT | a4d5e503edda970fc085e942018ee235622bfb11 | 2026-01-04T15:37:50.353881Z | false |
faker-ruby/faker | https://github.com/faker-ruby/faker/blob/a4d5e503edda970fc085e942018ee235622bfb11/lib/faker/blockchain/ethereum.rb | lib/faker/blockchain/ethereum.rb | # frozen_string_literal: true
module Faker
class Blockchain
class Ethereum < Base
class << self
##
# Produces a random Ethereum wallet address
#
# @return [String]
#
# @example
# Faker::Blockchain::Ethereum.address
# #=> "0xd392b0c0500700d02d27ab30805ec80ddd3320ff"
#
# @faker.version 1.9.1
def address
hex_alphabet = '0123456789abcdef'
var = +'0x'
40.times { var << sample(shuffle(hex_alphabet.chars)) }
var
end
end
end
end
end
| ruby | MIT | a4d5e503edda970fc085e942018ee235622bfb11 | 2026-01-04T15:37:50.353881Z | false |
faker-ruby/faker | https://github.com/faker-ruby/faker/blob/a4d5e503edda970fc085e942018ee235622bfb11/lib/faker/blockchain/tezos.rb | lib/faker/blockchain/tezos.rb | # frozen_string_literal: true
require 'openssl'
require 'securerandom'
module Faker
class Blockchain
class Tezos < Base
class << self
# @private
PREFIXES = {
tz1: [6, 161, 159],
KT1: [2, 90, 121],
edpk: [13, 15, 37, 217],
edsk: [13, 15, 58, 7],
edsig: [9, 245, 205, 134, 18],
B: [1, 52],
o: [5, 116]
}.freeze
##
# Produces a random Tezos account address
#
# @return [String]
#
# @example
# Faker::Blockchain::Tezos.account
# #=> "tz1eUsgK6aj752Fbxwk5sAoEFvSDnPjZ4qvk"
#
# @faker.version 1.9.2
def account
encode_tz(:tz1, 20)
end
##
# Produces a random Tezos contract
#
# @return [String]
#
# @example
# Faker::Blockchain::Tezos.contract
# #=> "KT1MroqeP15nnitB4CnNfkqHYa2NErhPPLWF"
#
# @faker.version 1.9.2
def contract
encode_tz(:KT1, 20)
end
##
# Produces a random Tezos operation
#
# @return [String]
#
# @example
# Faker::Blockchain::Tezos.operation
# #=> "onygWYXJX3xNstFLv9PcCrhQdCkENC795xwSinmTEc1jsDN4VDa"
#
# @faker.version 1.9.2
def operation
encode_tz(:o, 32)
end
##
# Produces a random Tezos block
#
# @return [String]
#
# @example
# Faker::Blockchain::Tezos.block
# #=> "BMbhs2rkY1dvAkAyRytvPsjFQ2RiPrBhYkxvWpY65dzkdSuw58a"
#
# @faker.version 1.9.4
def block
encode_tz(:B, 32)
end
##
# Produces a random Tezos signature
#
# @return [String]
#
# @example
# Faker::Blockchain::Tezos.signature
# #=> "edsigu165B7VFf3Dpw2QABVzEtCxJY2gsNBNcE3Ti7rRxtDUjqTFRpg67EdAQmY6YWPE5tKJDMnSTJDFu65gic8uLjbW2YwGvAZ"
#
# @faker.version 1.9.2
def signature
encode_tz(:edsig, 64)
end
##
# Produces a random Tezos public key
#
# @return [String]
#
# @example
# Faker::Blockchain::Tezos.public_key
# #=> "edpkuib9x8QXRc5nWwHUg7U1dXsVmaUrUNU5sX9pVEEvwbMVdfMCeq"
#
# @faker.version 2.15.2
def public_key
encode_tz(:edpk, 32)
end
##
# Produces a random Tezos public key
#
# @return [String]
#
# @example
# Faker::Blockchain::Tezos.secret_key
# #=> "edsk3HZCAGEGpzQPnQUwQeFY4ESanFhQCgLpKriQw8GHyhKCrjHawv"
#
# @faker.version 2.15.2
def secret_key
encode_tz(:edsk, 32)
end
protected
##
# @param prefix [Symbol]
# @param payload_size [Integer] The size of the payload
#
# @return [String]
def encode_tz(prefix, payload_size)
prefix = PREFIXES.fetch(prefix)
packed = prefix.map(&:chr).join + Faker::Config.random.bytes(payload_size)
checksum = OpenSSL::Digest::SHA256.digest(OpenSSL::Digest::SHA256.digest(packed))[0..3]
Faker::Base58.encode(packed + checksum)
end
end
end
end
end
| ruby | MIT | a4d5e503edda970fc085e942018ee235622bfb11 | 2026-01-04T15:37:50.353881Z | false |
faker-ruby/faker | https://github.com/faker-ruby/faker/blob/a4d5e503edda970fc085e942018ee235622bfb11/lib/faker/music/pearl_jam.rb | lib/faker/music/pearl_jam.rb | # frozen_string_literal: true
require_relative 'music'
module Faker
class Music
class PearlJam < Base
class << self
##
# Produces the name of a member of Pearl Jam (current and former)
#
# @return [String]
#
# @example
# Faker::Music::PearlJam.musician #=> "Eddie Vedder"
#
# @faker.version 2.13.0
def musician
fetch('pearl_jam.musicians')
end
##
# Produces the name of an album by Pearl Jam.
#
# @return [String]
#
# @example
# Faker::Music::PearlJam.album #=> "Ten"
#
# @faker.version 2.13.0
def album
fetch('pearl_jam.albums')
end
##
# Produces the name of a song by Pearl Jam.
#
# @return [String]
#
# @example
# Faker::Music::PearlJam.song #=> "Even Flow"
#
# @faker.version 2.13.0
def song
fetch('pearl_jam.songs')
end
end
end
end
end
| ruby | MIT | a4d5e503edda970fc085e942018ee235622bfb11 | 2026-01-04T15:37:50.353881Z | false |
faker-ruby/faker | https://github.com/faker-ruby/faker/blob/a4d5e503edda970fc085e942018ee235622bfb11/lib/faker/music/bossa_nova.rb | lib/faker/music/bossa_nova.rb | # frozen_string_literal: true
require_relative 'music'
module Faker
class Music
class BossaNova < Base
class << self
##
# Produces the name of a bossa nova artist.
#
# @return [String]
#
# @example
# Faker::Music::BossaNova.artist #=> "Tom Jobin"
#
# @faker.version 1.8.3
def artist
fetch('bossa_nova.artists')
end
##
# Produces a bossa nova song.
#
# @return [String]
#
# @example
# Faker::Music::BossaNova.song #=> "Chega de Saudade"
#
# @faker.version 1.8.3
def song
fetch('bossa_nova.songs')
end
end
end
end
include Faker::Deprecator
deprecate_generator('BossaNova', Music::BossaNova)
end
| ruby | MIT | a4d5e503edda970fc085e942018ee235622bfb11 | 2026-01-04T15:37:50.353881Z | false |
faker-ruby/faker | https://github.com/faker-ruby/faker/blob/a4d5e503edda970fc085e942018ee235622bfb11/lib/faker/music/phish.rb | lib/faker/music/phish.rb | # frozen_string_literal: true
module Faker
class Music
class Phish < Base
class << self
##
# Produces the name of a album by Phish.
#
# @return [String]
#
# @example
# Faker::Music::Phish.album #=> "Fuego"
#
# @faker.version 2.13.0
def album
fetch('phish.albums')
end
##
# Produces the name of a musician in Phish.
#
# @return [String]
#
# @example
# Faker::Music::Phish.musician #=> "Trey Anastasio"
#
# @faker.version 2.13.0
def musician
fetch('phish.musicians')
end
##
# Produces the name of a song by Phish.
#
# @return [String]
#
# @example
# Faker::Music::Phish.song #=> "Tweezer"
#
# @faker.version 1.9.2
def song
fetch('phish.songs')
end
end
end
end
end
| ruby | MIT | a4d5e503edda970fc085e942018ee235622bfb11 | 2026-01-04T15:37:50.353881Z | false |
faker-ruby/faker | https://github.com/faker-ruby/faker/blob/a4d5e503edda970fc085e942018ee235622bfb11/lib/faker/music/opera.rb | lib/faker/music/opera.rb | # frozen_string_literal: true
module Faker
# A generator of titles of operas by various composers
class Music
class Opera < Base
class << self
##
# Produces the title of an opera by Giuseppe Verdi.
#
# @return [String]
#
# @example
# Faker::Music::Opera.verdi #=> "Il Trovatore"
#
# @faker.version 1.9.4
def verdi
fetch('opera.italian.by_giuseppe_verdi')
end
##
# Produces the title of an opera by Gioacchino Rossini.
#
# @return [String]
#
# @example
# Faker::Music::Opera.rossini #=> "Il Barbiere di Siviglia"
#
# @faker.version 1.9.4
def rossini
fetch('opera.italian.by_gioacchino_rossini')
end
##
# Produces the title of an opera by Gaetano Donizetti.
#
# @return [String]
#
# @example
# Faker::Music::Opera.donizetti #=> "Lucia di Lammermoor"
#
# @faker.version 1.9.4
def donizetti
fetch('opera.italian.by_gaetano_donizetti')
end
##
# Produces the title of an opera by Vincenzo Bellini.
#
# @return [String]
#
# @example
# Faker::Music::Opera.bellini #=> "Norma"
#
# @faker.version 1.9.4
def bellini
fetch('opera.italian.by_vincenzo_bellini')
end
##
# Produces the title of an opera by Wolfgang Amadeus Mozart.
#
# @return [String]
#
# @example
# Faker::Music::Opera.mozart #=> "Die Zauberfloete"
#
# @faker.version next
def mozart
fetch('opera.italian.by_wolfgang_amadeus_mozart') +
fetch('opera.german.by_wolfgang_amadeus_mozart')
end
##
# Produces the title of an Italian opera by Wolfgang Amadeus Mozart.
#
# @return [String]
#
# @example
# Faker::Music::Opera.mozart_it #=> "Cosi fan tutte"
#
# @faker.version next
def mozart_italian
fetch('opera.italian.by_wolfgang_amadeus_mozart')
end
##
# Produces the title of a German opera by Wolfgang Amadeus Mozart.
#
# @return [String]
#
# @example
# Faker::Music::Opera.mozart_ger #=> "Die Zauberfloete"
#
# @faker.version next
def mozart_german
fetch('opera.german.by_wolfgang_amadeus_mozart')
end
##
# Produces the title of an opera by Christoph Willibald Gluck.
#
# @return [String]
#
# @example
# Faker::Music::Opera.gluck #=> "Orfeo ed Euridice"
#
# @faker.version next
def gluck
fetch('opera.italian.by_christoph_willibald_gluck') +
fetch('opera.french.by_christoph_willibald_gluck')
end
##
# Produces the title of an Italian opera by Christoph Willibald Gluck.
#
# @return [String]
#
# @example
# Faker::Music::Opera.gluck_it #=> "Orfeo ed Euridice"
#
# @faker.version next
def gluck_italian
fetch('opera.italian.by_christoph_willibald_gluck')
end
##
# Produces the title of a French opera by Christoph Willibald Gluck.
#
# @return [String]
#
# @example
# Faker::Music::Opera.gluck_fr #=> "Orphee et Euridice"
#
# @faker.version next
def gluck_french
fetch('opera.french.by_christoph_willibald_gluck')
end
##
# Produces the title of an opera by Ludwig van Beethoven.
#
# @return [String]
#
# @example
# Faker::Music::Opera.beethoven #=> "Fidelio"
#
# @faker.version next
def beethoven
fetch('opera.german.by_ludwig_van_beethoven')
end
##
# Produces the title of an opera by Carl Maria von Weber.
#
# @return [String]
#
# @example
# Faker::Music::Opera.weber #=> "Der Freischuetz"
#
# @faker.version next
def weber
fetch('opera.german.by_carl_maria_von_weber')
end
##
# Produces the title of an opera by Richard Strauss.
#
# @return [String]
#
# @example
# Faker::Music::Opera.strauss #=> "Elektra"
#
# @faker.version next
def strauss
fetch('opera.german.by_richard_strauss')
end
##
# Produces the title of an opera by Richard Wagner.
#
# @return [String]
#
# @example
# Faker::Music::Opera.wagner #=> "Tristan und Isolde"
#
# @faker.version next
def wagner
fetch('opera.german.by_richard_wagner')
end
##
# Produces the title of an opera by Robert Schumann.
#
# @return [String]
#
# @example
# Faker::Music::Opera.schumann #=> "Genoveva"
#
# @faker.version next
def schumann
fetch('opera.german.by_robert_schumann')
end
##
# Produces the title of an opera by Franz Schubert.
#
# @return [String]
#
# @example
# Faker::Music::Opera.schubert #=> "Alfonso und Estrella"
#
# @faker.version next
def schubert
fetch('opera.german.by_franz_schubert')
end
##
# Produces the title of an opera by Alban Berg.
#
# @return [String]
#
# @example
# Faker::Music::Opera.berg #=> "Wozzeck"
#
# @faker.version next
def berg
fetch('opera.german.by_alban_berg')
end
##
# Produces the title of an opera by Maurice Ravel.
#
# @return [String]
#
# @example
# Faker::Music::Opera.ravel #=> "L'enfant et les sortileges"
#
# @faker.version next
def ravel
fetch('opera.french.by_maurice_ravel')
end
##
# Produces the title of an opera by Hector Berlioz.
#
# @return [String]
#
# @example
# Faker::Music::Opera.berlioz #=> "Les Troyens"
#
# @faker.version next
def berlioz
fetch('opera.french.by_hector_berlioz')
end
##
# Produces the title of an opera by Georges Bizet.
#
# @return [String]
#
# @example
# Faker::Music::Opera.bizet #=> "Carmen"
#
# @faker.version next
def bizet
fetch('opera.french.by_georges_bizet')
end
##
# Produces the title of an opera by Charles Gounod.
#
# @return [String]
#
# @example
# Faker::Music::Opera.gounod #=> "Faust"
#
# @faker.version next
def gounod
fetch('opera.french.by_charles_gounod')
end
##
# Produces the title of an opera by Camille Saint-Saens.
#
# @return [String]
#
# @example
# Faker::Music::Opera.saint_saens #=> "Samson and Delilah"
#
# @faker.version next
def saint_saens
fetch('opera.french.by_camille_saint_saens')
end
end
end
end
end
| ruby | MIT | a4d5e503edda970fc085e942018ee235622bfb11 | 2026-01-04T15:37:50.353881Z | false |
faker-ruby/faker | https://github.com/faker-ruby/faker/blob/a4d5e503edda970fc085e942018ee235622bfb11/lib/faker/music/umphreys_mcgee.rb | lib/faker/music/umphreys_mcgee.rb | # frozen_string_literal: true
module Faker
class Music
class UmphreysMcgee < Base
class << self
##
# Produces the name of a song by Umphrey's McGee.
#
# @return [String]
#
# @example
# Faker::Music::UmphreysMcgee.song #=> "Dump City"
#
# @faker.version 1.8.3
def song
fetch('umphreys_mcgee.song')
end
end
end
end
end
| ruby | MIT | a4d5e503edda970fc085e942018ee235622bfb11 | 2026-01-04T15:37:50.353881Z | false |
faker-ruby/faker | https://github.com/faker-ruby/faker/blob/a4d5e503edda970fc085e942018ee235622bfb11/lib/faker/music/rock_band.rb | lib/faker/music/rock_band.rb | # frozen_string_literal: true
module Faker
class Music
class RockBand < Base
class << self
##
# Produces the name of a rock band.
#
# @return [String]
#
# @example
# Faker::Music::RockBand.name #=> "Led Zeppelin"
#
# @faker.version 1.7.0
def name
fetch('rock_band.name')
end
# Produces a rock song.
#
# @return [String]
#
# @example
# Faker::Music::RockBand.song #=> "Dani California"
#
# @faker.version next
def song
fetch('rock_band.song')
end
end
end
end
end
| ruby | MIT | a4d5e503edda970fc085e942018ee235622bfb11 | 2026-01-04T15:37:50.353881Z | false |
faker-ruby/faker | https://github.com/faker-ruby/faker/blob/a4d5e503edda970fc085e942018ee235622bfb11/lib/faker/music/prince.rb | lib/faker/music/prince.rb | # frozen_string_literal: true
module Faker
class Music
class Prince < Base
class << self
##
# Produces a random Prince song.
#
# @return [String]
#
# @example
# Faker::Music::Prince.song #=> "Raspberry Beret"
# Faker::Music::Prince.song #=> "Starfish And Coffee"
#
# @faker.version 2.13.0
def song
fetch('prince.song')
end
##
# Produces a random Prince song lyric.
#
# @return [String]
#
# @example
# Faker::Music::Prince.lyric #=> "Dearly beloved, we are gathered here today to get through this thing called life."
# Faker::Music::Prince.lyric #=> "You were so hard to find, the beautiful ones, they hurt you every time."
#
# @faker.version 2.13.0
def lyric
fetch('prince.lyric')
end
##
# Produces a random Prince album.
#
# @return [String]
#
# @example
# Faker::Music::Prince.album #=> "The Gold Experience"
# Faker::Music::Prince.album #=> "Purple Rain"
#
# @faker.version 2.13.0
def album
fetch('prince.album')
end
##
# Produces a random Prince-associated band.
#
# @return [String]
#
# @example
# Faker::Music::Prince.band #=> "The New Power Generation"
#
# @faker.version 2.13.0
def band
fetch('prince.band')
end
end
end
end
end
| ruby | MIT | a4d5e503edda970fc085e942018ee235622bfb11 | 2026-01-04T15:37:50.353881Z | false |
faker-ruby/faker | https://github.com/faker-ruby/faker/blob/a4d5e503edda970fc085e942018ee235622bfb11/lib/faker/music/rush.rb | lib/faker/music/rush.rb | # frozen_string_literal: true
require_relative 'music'
module Faker
class Music
class Rush < Base
class << self
##
# Produces the name of a member of Rush
#
# @return [String]
#
# @example
# Faker::Music::Rush.player #=> "Geddy Lee"
#
# @faker.version 2.13.0
def player
fetch('rush.players')
end
##
# Produces the name of an album by Rush
#
# @return [String]
#
# @example
# Faker::Music::Rush.album #=> "Hold Your Fire"
#
# @faker.version 2.13.0
def album
fetch('rush.albums')
end
end
end
end
end
| ruby | MIT | a4d5e503edda970fc085e942018ee235622bfb11 | 2026-01-04T15:37:50.353881Z | false |
faker-ruby/faker | https://github.com/faker-ruby/faker/blob/a4d5e503edda970fc085e942018ee235622bfb11/lib/faker/music/smashing_pumpkins.rb | lib/faker/music/smashing_pumpkins.rb | # frozen_string_literal: true
require_relative 'music'
module Faker
class Music
class SmashingPumpkins < Base
class << self
##
# Produces the name of a member of the Smashing Pumpkins (current and former)
#
# @return [String]
#
# @example
# Faker::Music::SmashingPumpkins.musician #=> "Billy Corgan"
#
# @faker.version next
def musician
fetch('smashing_pumpkins.musicians')
end
##
# Produces the name of an album by the Smashing Pumpkins.
#
# @return [String]
#
# @example
# Faker::Music::SmashingPumpkins.album #=> "Siamese Dream"
#
# @faker.version next
def album
fetch('smashing_pumpkins.albums')
end
##
# Produces a random Smashing Pumpkins song lyric.
#
# @return [String]
#
# @example
# Faker::Music::SmashingPumpkins.lyric #=> "Despite all my rage, I am still just a rat in a cage"
# Faker::Music::SmashingPumpkins.lyric #=> "Breathin' underwater, and livin' under glass"
#
# @faker.version next
def lyric
fetch('smashing_pumpkins.lyric')
end
##
# Produces the name of a song by the Smashing Pumpkins.
#
# @return [String]
#
# @example
# Faker::Music::SmashingPumpkins.song #=> "Stand Inside My Love"
#
# @faker.version next
def song
fetch('smashing_pumpkins.songs')
end
end
end
end
end
| ruby | MIT | a4d5e503edda970fc085e942018ee235622bfb11 | 2026-01-04T15:37:50.353881Z | false |
faker-ruby/faker | https://github.com/faker-ruby/faker/blob/a4d5e503edda970fc085e942018ee235622bfb11/lib/faker/music/grateful_dead.rb | lib/faker/music/grateful_dead.rb | # frozen_string_literal: true
require_relative 'music'
module Faker
class Music
class GratefulDead < Base
class << self
##
# Produces the name of a member of The Grateful Dead.
#
# @return [String]
#
# @example
# Faker::Music::GratefulDead.player #=> "Jerry Garcia"
#
# @faker.version 1.9.2
def player
fetch('grateful_dead.players')
end
##
# Produces the name of a song by The Grateful Dead.
#
# @return [String]
#
# @example
# Faker::Music::GratefulDead.song #=> "Cassidy"
#
# @faker.version 1.9.2
def song
fetch('grateful_dead.songs')
end
end
end
end
end
| ruby | MIT | a4d5e503edda970fc085e942018ee235622bfb11 | 2026-01-04T15:37:50.353881Z | false |
faker-ruby/faker | https://github.com/faker-ruby/faker/blob/a4d5e503edda970fc085e942018ee235622bfb11/lib/faker/music/music.rb | lib/faker/music/music.rb | # frozen_string_literal: true
module Faker
class Music < Base
class << self
NOTE_LETTERS = %w[C D E F G A B].freeze
ACCIDENTAL_SIGNS = ['b', '#', ''].freeze
KEY_TYPES = ['', 'm'].freeze
CHORD_TYPES = ['', 'maj', '6', 'maj7', 'm', 'm7', '-7', '7', 'dom7', 'dim', 'dim7', 'm7b5'].freeze
##
# Produces the name of a key/note, using letter notation.
#
# @return [String]
#
# @example
# Faker::Music.key #=> "A#"
#
# @faker.version 1.6.4
def key
sample(keys) + sample(key_variants)
end
##
# Produces the name of a chord, using letter notation.
#
# @return [String]
#
# @example
# Faker::Music.chord #=> "Adim7"
#
# @faker.version 1.6.4
def chord
key + sample(chord_types)
end
##
# Produces the name of an instrument.
#
# @return [String]
#
# @example
# Faker::Music.instrument #=> "Acoustic Guitar"
#
# @faker.version 1.6.4
def instrument
fetch('music.instruments')
end
##
# Produces an array of the letter names of musical notes, without accidentals.
#
# @return [Array<String>]
#
# @faker.version 1.6.4
def keys
NOTE_LETTERS
end
##
# Produces an array of accidentals (with "natural" denoted as an empty string).
#
# @return [Array<String>]
#
# @faker.version 1.6.4
def key_variants
ACCIDENTAL_SIGNS
end
##
# Produces an array of key types (with "major" denoted as an empty string).
#
# @return [Array<String>]
#
# @example
# Faker::Music.key_types #=> ['', 'm']
#
# @faker.version 1.6.4
def key_types
KEY_TYPES
end
##
# Produces an array of types of chords.
#
# @return [Array<String>]
#
# @faker.version 1.6.4
def chord_types
CHORD_TYPES
end
##
# Produces the name of a band.
#
# @return [String]
#
# @example
# Faker::Music.band #=> "The Beatles"
#
# @faker.version 1.9.1
def band
fetch('music.bands')
end
##
# Produces the name of an album.
#
# @return [String]
#
# @example
# Faker::Music.album #=> "Sgt. Pepper's Lonely Hearts Club"
#
# @faker.version 1.9.1
def album
fetch('music.albums')
end
##
# Produces the name of a musical genre.
#
# @return [String]
#
# @example
# Faker::Music.genre #=> "Rock"
#
# @faker.version 1.9.1
def genre
fetch('music.genres')
end
##
# Produces a name from Lou Bega's Mambo #5
#
# @return [String]
#
# @example
# Faker::Music.mambo #=> "Monica"
# @faker.version next
def mambo_no_5
fetch('music.mambo_no_5')
end
end
end
end
| ruby | MIT | a4d5e503edda970fc085e942018ee235622bfb11 | 2026-01-04T15:37:50.353881Z | false |
faker-ruby/faker | https://github.com/faker-ruby/faker/blob/a4d5e503edda970fc085e942018ee235622bfb11/lib/faker/music/hiphop.rb | lib/faker/music/hiphop.rb | # frozen_string_literal: true
module Faker
class Music
class Hiphop < Base
class << self
##
# Produces the name of a Hip Hop Artist
#
# @return [String]
#
# @example
# Faker::Music::Hiphop.artist #=> "Lil Wayne"
#
# @faker.version next
def artist
fetch('music.hiphop.artist')
end
##
# Produces the name of a Hip Hop Group
#
# @return [String]
#
# @example
# Faker::Music::Hiphop.groups #=> "OVO"
#
# @faker.version next
def groups
fetch('music.hiphop.groups')
end
##
# Produces the name of a Hip Hop Subgenre
#
# @return [String]
#
# @example
# Faker::Music::Hiphop.subgeneres #=> "Alternative"
#
# @faker.version next
def subgenres
fetch('music.hiphop.subgenres')
end
end
end
end
end
| ruby | MIT | a4d5e503edda970fc085e942018ee235622bfb11 | 2026-01-04T15:37:50.353881Z | false |
faker-ruby/faker | https://github.com/faker-ruby/faker/blob/a4d5e503edda970fc085e942018ee235622bfb11/lib/faker/default/vehicle.rb | lib/faker/default/vehicle.rb | # frozen_string_literal: true
module Faker
class Vehicle < Base
flexible :vehicle
MILEAGE_MIN = 10_000
MILEAGE_MAX = 90_000
VIN_KEYSPACE = %w[A B C D E F G H J K L M N P R S T U V W X Y Z 0 1 2 3 4 5 6 7 8 9].freeze
VIN_TRANSLITERATION = { A: 1, B: 2, C: 3, D: 4, E: 5, F: 6, G: 7, H: 8, J: 1, K: 2, L: 3, M: 4, N: 5, P: 7, R: 9, S: 2, T: 3, U: 4, V: 5, W: 6, X: 7, Y: 8, Z: 9 }.freeze
VIN_WEIGHT = [8, 7, 6, 5, 4, 3, 2, 10, 0, 9, 8, 7, 6, 5, 4, 3, 2].freeze
SG_CHECKSUM_WEIGHTS = [3, 14, 2, 12, 2, 11, 1].freeze
SG_CHECKSUM_CHARS = 'AYUSPLJGDBZXTRMKHEC'
class << self
# Produces a random vehicle VIN number.
#
# @return [String]
#
# @example
# Faker::Vehicle.vin #=> "LLDWXZLG77VK2LUUF"
#
# @faker.version 1.6.4
def vin
generate(:string) do |g|
g.letter(name: :wmi, ranges: ['100'..'199', '400'..'499', '500'..'599', '700'..'799', '7A0'..'7F9'])
g.letter(name: :vds, length: 5, ranges: [VIN_KEYSPACE])
g.computed(name: :checksum, deps: %i[wmi vds model_year plant_code vis]) do |wmi, vds, model_year, plant_code, vis|
checksum = "#{wmi}#{vds}0#{model_year}#{plant_code}#{vis}".chars.each_with_index.map do |char, i|
value = (char =~ /\A\d\z/ ? char.to_i : VIN_TRANSLITERATION[char.to_sym])
value * VIN_WEIGHT[i]
end.inject(:+) % 11
if checksum == 10
'X'
else
checksum
end
end
g.letter(name: :model_year, length: 1, ranges: [VIN_KEYSPACE - %w[U Z 0]])
g.letter(name: :plant_code, length: 1, ranges: [VIN_KEYSPACE])
g.int(name: :vis, length: 6)
end
end
# Produces a random vehicle manufacturer.
#
# @return [String]
#
# @example
# Faker::Vehicle.manufacturer #=> "Lamborghini"
#
# @faker.version 1.6.4
def manufacturer
fetch('vehicle.manufacturer')
end
alias manufacture manufacturer
##
# Produces a random vehicle make.
#
# @return [String]
#
# @example
# Faker::Vehicle.make #=> "Honda"
#
# @faker.version 1.6.4
def make
fetch('vehicle.makes')
end
##
# Produces a random vehicle model.
#
# @param make_of_model [String] Specific valid vehicle make.
# @return [String]
#
# @example
# Faker::Vehicle.model #=> "A8"
# Faker::Vehicle.model(make_of_model: 'Toyota') #=> "Prius"
#
# @faker.version 1.6.4
def model(make_of_model: '')
return fetch("vehicle.models_by_make.#{make}") if make_of_model.empty?
fetch("vehicle.models_by_make.#{make_of_model}")
end
##
# Produces a random vehicle make and model.
#
# @return [String]
#
# @example
# Faker::Vehicle.make_and_model #=> "Dodge Charger"
#
# @faker.version 1.6.4
def make_and_model
m = make
"#{m} #{model(make_of_model: m)}"
end
##
# Produces a random vehicle style.
#
# @return [String]
#
# @example
# Faker::Vehicle.style #=> "ESi"
#
# @faker.version 1.6.4
def style
fetch('vehicle.styles')
end
##
# Produces a random vehicle color.
#
# @return [String]
#
# @example
# Faker::Vehicle.color #=> "Red"
#
# @faker.version 1.6.4
def color
fetch('vehicle.colors')
end
##
# Produces a random vehicle transmission.
#
# @return [String]
#
# @example
# Faker::Vehicle.transmission #=> "Automanual"
#
# @faker.version 1.6.4
def transmission
fetch('vehicle.transmissions')
end
##
# Produces a random vehicle drive type.
#
# @return [String]
#
# @example
# Faker::Vehicle.drive_type #=> "4x2/2-wheel drive"
#
# @faker.version 1.6.4
def drive_type
fetch('vehicle.drive_types')
end
##
# Produces a random vehicle fuel type.
#
# @return [String]
#
# @example
# Faker::Vehicle.fuel_type #=> "Diesel"
#
# @faker.version 1.6.4
def fuel_type
fetch('vehicle.fuel_types')
end
##
# Produces a random car type.
#
# @return [String]
#
# @example
# Faker::Vehicle.car_type #=> "Sedan"
#
# @faker.version 1.6.4
def car_type
fetch('vehicle.car_types')
end
##
# Produces a random engine cylinder count.
#
# @return [String]
#
# @example
# Faker::Vehicle.engine_size #=> 6
# Faker::Vehicle.engine #=> 4
#
# @faker.version 1.6.4
def engine
"#{sample(fetch_all('vehicle.doors'))} #{fetch('vehicle.cylinder_engine')}"
end
alias engine_size engine
##
# Produces a random list of car options.
#
# @return [Array<String>]
#
# @example
# Faker::Vehicle.car_options #=> ["DVD System", "MP3 (Single Disc)", "Tow Package", "CD (Multi Disc)", "Cassette Player", "Bucket Seats", "Cassette Player", "Leather Interior", "AM/FM Stereo", "Third Row Seats"]
#
# @faker.version 1.6.4
def car_options
Array.new(rand(5...10)) { fetch('vehicle.car_options') }
end
##
# Produces a random list of standard specs.
#
# @return [Array<String>]
#
# @example
# Faker::Vehicle.standard_specs #=> ["Full-size spare tire w/aluminum alloy wheel", "Back-up camera", "Carpeted cargo area", "Silver accent IP trim finisher -inc: silver shifter finisher", "Back-up camera", "Water-repellent windshield & front door glass", "Floor carpeting"]
#
# @faker.version 1.6.4
def standard_specs
Array.new(rand(5...10)) { fetch('vehicle.standard_specs') }
end
##
# Produces a random vehicle door count.
#
# @return [Integer]
#
# @example
# Faker::Vehicle.doors #=> 1
# Faker::Vehicle.door_count #=> 3
#
# @faker.version 1.6.4
def doors
sample(fetch_all('vehicle.doors'))
end
alias door_count doors
##
# Produces a random car year between 1 and 15 years ago.
#
# @return [Integer]
#
# @example
# Faker::Vehicle.year #=> 2008
#
# @faker.version 1.6.4
def year
Faker::Time.backward(days: rand_in_range(365, 5475), period: :all, format: '%Y').to_i
end
##
# Produces a random mileage/kilometrage for a vehicle.
#
# @param min [Integer] Specific minimum limit for mileage generation.
# @param max [Integer] Specific maximum limit for mileage generation.
# @return [Integer]
#
# @example
# Faker::Vehicle.mileage #=> 26961
# Faker::Vehicle.mileage(min: 50_000) #=> 81557
# Faker::Vehicle.mileage(min: 50_000, max: 250_000) #=> 117503
# Faker::Vehicle.kilometrage #=> 35378
#
# @faker.version 1.6.4
def mileage(min: MILEAGE_MIN, max: MILEAGE_MAX)
rand_in_range(min, max)
end
alias kilometrage mileage
##
# Produces a random license plate number.
#
# @param state_abbreviation [String] Two letter state abbreviation for license plate generation.
# @return [String]
#
# @example
# Faker::Vehicle.license_plate #=> "DEP-2483"
# Faker::Vehicle.license_plate(state_abbreviation: 'FL') #=> "977 UNU"
#
# @faker.version 1.6.4
def license_plate(state_abbreviation: '')
return regexify(bothify(fetch('vehicle.license_plate'))) if state_abbreviation.empty?
key = "vehicle.license_plate_by_state.#{state_abbreviation}"
regexify(bothify(fetch(key)))
end
##
# Produces a random license plate number for Singapore.
#
# @return [String]
#
# @example
# Faker::Vehicle.singapore_license_plate #=> "SLV1854M"
#
# @faker.version 1.6.4
def singapore_license_plate
key = 'vehicle.license_plate'
plate_number = regexify(bothify(fetch(key)))
"#{plate_number}#{singapore_checksum(plate_number)}"
end
##
# Produces a car version
#
# @return [String]
#
# @example
# Faker::Vehicle.version #=> "40 TFSI Premium"
#
# @faker.version next
def version
fetch('vehicle.version')
end
private
def singapore_checksum(plate_number)
padded_alphabets = format('%3s', plate_number[/^[A-Z]+/]).tr(' ', '-').chars
padded_digits = format('%04d', plate_number[/\d+/]).chars.map(&:to_i)
sum = [*padded_alphabets, *padded_digits].each_with_index.reduce(0) do |memo, (char, i)|
value = char.is_a?(Integer) ? char : char.ord - 64
memo + (SG_CHECKSUM_WEIGHTS[i] * value)
end
SG_CHECKSUM_CHARS.chars[sum % 19]
end
end
end
end
| ruby | MIT | a4d5e503edda970fc085e942018ee235622bfb11 | 2026-01-04T15:37:50.353881Z | false |
faker-ruby/faker | https://github.com/faker-ruby/faker/blob/a4d5e503edda970fc085e942018ee235622bfb11/lib/faker/default/demographic.rb | lib/faker/default/demographic.rb | # frozen_string_literal: true
module Faker
class Demographic < Base
class << self
##
# Produces the name of a race.
#
# @return [String]
#
# @example
# Faker::Demographic.race #=> "Native Hawaiian or Other Pacific Islander"
#
# @faker.version 1.7.3
def race
fetch('demographic.race')
end
##
# Produces a level of educational attainment.
#
# @return [String]
#
# @example
# Faker::Demographic.educational_attainment #=> "GED or alternative credential"
#
# @faker.version 1.7.3
def educational_attainment
fetch('demographic.educational_attainment')
end
##
# Produces a denonym.
#
# @return [String]
#
# @example
# Faker::Demographic.denonym #=> "Panamanian"
#
# @faker.version 1.7.3
def demonym
fetch('demographic.demonym')
end
##
# Produces a marital status.
#
# @return [String]
#
# @example
# Faker::Demographic.marital_status #=> "Widowed"
#
# @faker.version 1.7.3
def marital_status
fetch('demographic.marital_status')
end
##
# Produces a sex for demographic purposes.
#
# @return [String]
#
# @example
# Faker::Demographic.sex #=> "Female"
#
# @faker.version 1.7.3
def sex
fetch('demographic.sex')
end
##
# Produces a height as a string.
#
# @param unit [Symbol] either `:metric` or `imperial`.
# @return [String]
#
# @example
# Faker::Demographic.height #=> "1.61"
# @example
# Faker::Demographic.height(unit: :imperial) #=> "6 ft, 2 in"
#
# @faker.version 1.7.3
def height(unit: :metric)
case unit
when :imperial
inches = rand_in_range(57, 86)
"#{inches / 12} ft, #{inches % 12} in"
when :metric
rand_in_range(1.45, 2.13).round(2).to_s
end
end
end
end
end
| ruby | MIT | a4d5e503edda970fc085e942018ee235622bfb11 | 2026-01-04T15:37:50.353881Z | false |
faker-ruby/faker | https://github.com/faker-ruby/faker/blob/a4d5e503edda970fc085e942018ee235622bfb11/lib/faker/default/food.rb | lib/faker/default/food.rb | # frozen_string_literal: true
module Faker
class Food < Base
flexible :food
class << self
##
# Retrieves an allergen.
#
# @return [String]
#
# @example
# Faker::Food.allergen #=> "Peanuts"
#
# @faker.version next
def allergen
fetch('food.allergens')
end
##
# Retrieves a typical dish from each country.
#
# @return [String]
#
# @example
# Faker::Food.dish #=> "Feijoada"
#
# @faker.version 1.8.0
def dish
fetch('food.dish')
end
##
# Retrieves a description about some dish
#
# @return [String]
#
# @example
# Faker::Food.description #=> "Breaded fried chicken with waffles. Served with maple syrup."
#
# @faker.version 1.9.0
def description
fetch('food.descriptions')
end
##
# Retrieves an ingredient
#
# @return [String]
#
# @example
# Faker::Food.ingredient #=> "Olives"
#
# @faker.version 1.7.0
def ingredient
fetch('food.ingredients')
end
##
# Retrieves a fruit
#
# @return [String]
#
# @example
# Faker::Food.fruits #=> "Papaya"
#
# @faker.version 1.9.0
def fruits
fetch('food.fruits')
end
##
# Retrieves a vegetable
#
# @return [String]
#
# @example
# Faker::Food.vegetables #=> "Broccolini"
#
# @faker.version 1.9.0
def vegetables
fetch('food.vegetables')
end
##
# Retrieves some random spice
#
# @return [String]
#
# @example
# Faker::Food.spice #=> "Garlic Chips"
#
# @faker.version 1.7.0
def spice
fetch('food.spices')
end
##
# Retrieves cooking measures
#
# @return [String]
#
# @example
# Faker::Food.measurement #=> "1/3"
#
# @faker.version 1.7.0
def measurement
"#{fetch('food.measurement_sizes')} #{fetch('food.measurements')}"
end
##
# Retrieves metric measurements
#
# @return [String]
#
# @example
# Faker::Food.metric_measurement #=> "centiliter"
#
# @faker.version 1.8.3
def metric_measurement
fetch('food.metric_measurements')
end
##
# Retrieves ethnic category
#
# @return [String]
#
# @example
# Faker::Food.ethnic_category #=> "Indian cuisine"
#
# @faker.version next
def ethnic_category
fetch('food.ethnic_category')
end
end
end
end
| ruby | MIT | a4d5e503edda970fc085e942018ee235622bfb11 | 2026-01-04T15:37:50.353881Z | false |
faker-ruby/faker | https://github.com/faker-ruby/faker/blob/a4d5e503edda970fc085e942018ee235622bfb11/lib/faker/default/hacker.rb | lib/faker/default/hacker.rb | # frozen_string_literal: true
module Faker
# Port of http://shinytoylabs.com/jargon/
# Are you having trouble writing tech-savvy dialogue for your latest screenplay?
# Worry not! Hollywood-grade technical talk is ready to fill out any form where you need to look smart.
class Hacker < Base
flexible :hacker
class << self
##
# Produces something smart.
#
# @return [String]
#
# @example
# Faker::Hacker.say_something_smart
# #=> "Try to compress the SQL interface, maybe it will program the back-end hard drive!"
#
# @faker.version 1.4.0
def say_something_smart
sample(phrases)
end
##
# Short technical abbreviations.
#
# @return [String]
#
# @example
# Faker::Hacker.abbreviation #=> "RAM"
#
# @faker.version 1.4.0
def abbreviation
fetch('hacker.abbreviation')
end
##
# Hacker-centric adjectives.
#
# @return [String]
#
# @example
# Faker::Hacker.adjective #=> "open-source"
#
# @faker.version 1.4.0
def adjective
fetch('hacker.adjective')
end
##
# Only the best hacker-related nouns.
#
# @return [String]
#
# @example
# Faker::Hacker.noun #=> "bandwidth"
#
# @faker.version 1.4.0
def noun
fetch('hacker.noun')
end
##
# Actions that hackers take.
#
# @return [String]
#
# @example
# Faker::Hacker.verb #=> "bypass"
#
# @faker.version 1.4.0
def verb
fetch('hacker.verb')
end
##
# Produces a verb that ends with '-ing'.
#
# @return [String]
#
# @example
# Faker::Hacker.ingverb #=> "synthesizing"
#
# @faker.version 1.4.0
def ingverb
fetch('hacker.ingverb')
end
# @private
def phrases
["If we #{verb} the #{noun}, we can get to the #{abbreviation} #{noun} through the #{adjective} #{abbreviation} #{noun}!",
"We need to #{verb} the #{adjective} #{abbreviation} #{noun}!",
"Try to #{verb} the #{abbreviation} #{noun}, maybe it will #{verb} the #{adjective} #{noun}!",
"You can't #{verb} the #{noun} without #{ingverb} the #{adjective} #{abbreviation} #{noun}!",
"Use the #{adjective} #{abbreviation} #{noun}, then you can #{verb} the #{adjective} #{noun}!",
"The #{abbreviation} #{noun} is down, #{verb} the #{adjective} #{noun} so we can #{verb} the #{abbreviation} #{noun}!",
"#{ingverb} the #{noun} won't do anything, we need to #{verb} the #{adjective} #{abbreviation} #{noun}!".capitalize,
"I'll #{verb} the #{adjective} #{abbreviation} #{noun}, that should #{noun} the #{abbreviation} #{noun}!"]
end
end
end
end
| ruby | MIT | a4d5e503edda970fc085e942018ee235622bfb11 | 2026-01-04T15:37:50.353881Z | false |
faker-ruby/faker | https://github.com/faker-ruby/faker/blob/a4d5e503edda970fc085e942018ee235622bfb11/lib/faker/default/adjective.rb | lib/faker/default/adjective.rb | # frozen_string_literal: true
module Faker
class Adjective < Base
flexible :adjective
class << self
##
# Produces a positive adjective.
#
# @return [String]
#
# @example
# Faker::Adjective.positive #=> "Kind"
#
# @faker.version next
def positive
fetch('adjective.positive')
end
##
# Produces a negative adjective.
#
# @return [String]
#
# @example
# Faker::Adjective.negative #=> "Creepy"
#
# @faker.version next
def negative
fetch('adjective.negative')
end
end
end
end
| ruby | MIT | a4d5e503edda970fc085e942018ee235622bfb11 | 2026-01-04T15:37:50.353881Z | false |
faker-ruby/faker | https://github.com/faker-ruby/faker/blob/a4d5e503edda970fc085e942018ee235622bfb11/lib/faker/default/subscription.rb | lib/faker/default/subscription.rb | # frozen_string_literal: true
module Faker
class Subscription < Base
##
# Produces the name of a subscription plan.
#
# @return [String]
#
# @example
# Faker::Subscription.plan #=> "Platinum"
#
# @faker.version 1.9.2
def self.plan
fetch('subscription.plans')
end
##
# Produces a subscription status.
#
# @return [String]
#
# @example
# Faker::Subscription.status #=> "Active"
#
# @faker.version 1.9.2
def self.status
fetch('subscription.statuses')
end
##
# Produces the name of a payment method.
#
# @return [String]
#
# @example
# Faker::Subscription.payment_method #=> "PayPal"
#
# @faker.version 1.9.2
def self.payment_method
fetch('subscription.payment_methods')
end
##
# Produces the name of a subscription term.
#
# @return [String]
#
# @example
# Faker::Subscription.subscription_term #=> "Annual"
#
# @faker.version 1.9.2
def self.subscription_term
fetch('subscription.subscription_terms')
end
##
# Produces the name of a payment term.
#
# @return [String]
#
# @example
# Faker::Subscription.payment_term #=> "Monthly"
#
# @faker.version 1.9.2
def self.payment_term
fetch('subscription.payment_terms')
end
end
end
| ruby | MIT | a4d5e503edda970fc085e942018ee235622bfb11 | 2026-01-04T15:37:50.353881Z | false |
faker-ruby/faker | https://github.com/faker-ruby/faker/blob/a4d5e503edda970fc085e942018ee235622bfb11/lib/faker/default/industry_segments.rb | lib/faker/default/industry_segments.rb | # frozen_string_literal: true
module Faker
class IndustrySegments < Base
flexible :industry_segments
class << self
##
# Produces the name of an industry.
#
# @return [String]
#
# @example
# Faker::IndustrySegments.industry #=> "Basic Materials"
#
# @faker.version 1.9.2
def industry
fetch('industry_segments.industry')
end
##
# Produces the name of a super-sector of an industry.
#
# @return [String]
#
# @example
# Faker::IndustrySegments.super_sector #=> "Basic Resources"
#
# @faker.version 1.9.2
def super_sector
fetch('industry_segments.super_sector')
end
##
# Produces the name of a sector of an industry.
#
# @return [String]
#
# @example
# Faker::IndustrySegments.sector #=> "Industrial Metals & Mining"
#
# @faker.version 1.9.2
def sector
fetch('industry_segments.sector')
end
##
# Produces the name of a subsector of an industry.
#
# @return [String]
#
# @example
# Faker::IndustrySegments.industry #=> "Basic Materials"
#
# @faker.version 1.9.2
def sub_sector
fetch('industry_segments.sub_sector')
end
end
end
end
| ruby | MIT | a4d5e503edda970fc085e942018ee235622bfb11 | 2026-01-04T15:37:50.353881Z | false |
faker-ruby/faker | https://github.com/faker-ruby/faker/blob/a4d5e503edda970fc085e942018ee235622bfb11/lib/faker/default/drone.rb | lib/faker/default/drone.rb | # frozen_string_literal: true
module Faker
class Drone < Base
class << self
##
# Returns random drone name with company
#
# @return [string]
#
# @example
# Faker::Drone.name #=> "DJI Mavic Air 2"
#
# @faker.version 2.14.0
def name
fetch('drone.name')
end
##
# Returns total drone weight in grams
#
# @return [String]
#
# @example
# Faker::Drone.weight #=> "570 g"
#
# @faker.version 2.14.0
def weight
parse('drone.weight')
end
##
# Returns maximum ascent speed for drone in m/s
#
# @return [String]
#
# @example
# Faker::Drone.max_ascent_speed #=> "4 m/s"
#
# @faker.version 2.14.0
def max_ascent_speed
parse('drone.max_ascent_speed')
end
##
# Returns maximum descent speed for drone in m/s
#
# @return [String]
#
# @example
# Faker::Drone.max_descent_speed #=> "4 m/s"
#
# @faker.version 2.14.0
def max_descent_speed
parse('drone.max_descent_speed')
end
##
# Returns max flight time for drone in optimal conditions
#
# @return [String]
#
# @example
# Faker::Drone.flight_time #=> "34 min"
#
# @faker.version 2.14.0
def flight_time
parse('drone.flight_time')
end
##
# Returns max altitude drone can go above sea level in meters
#
# @return [String]
#
# @example
# Faker::Drone.max_altitude #=> "5000 m"
#
# @faker.version 2.14.0
def max_altitude
parse('drone.max_altitude')
end
##
# Returns how far drone can go in optimal condition when full charged in meters
#
# @return [String]
#
# @example
# Faker::Drone.max_flight_distance #=> "18500 m"
#
# @faker.version 2.14.0
def max_flight_distance
parse('drone.max_flight_distance')
end
##
# Returns max horizontal speed by drone in m/s
#
# @return [String]
#
# @example
# Faker::Drone.max_speed #=> "19 m/s"
#
# @faker.version 2.14.0
def max_speed
parse('drone.max_speed')
end
##
# Returns max wind resistance by drone in m/s
#
# @return [String]
#
# @example
# Faker::Drone.max_wind_resistance #=> "10.5 m/s"
#
# @faker.version 2.14.0
def max_wind_resistance
parse('drone.max_wind_resistance')
end
##
# Returns max angular velocity of drone in degrees/s
#
# @return [String]
#
# @example
# Faker::Drone.max_angular_velocity #=> "250 degree/s"
#
# @faker.version 2.14.0
def max_angular_velocity
parse('drone.max_angular_velocity')
end
##
# Returns max tilt angle drone can go in degrees
#
# @return [String]
#
# @example
# Faker::Drone.max_tilt_angle #=> "35 degrees"
#
# @faker.version 2.14.0
def max_tilt_angle
parse('drone.max_tilt_angle')
end
##
# Returns operating temperature for drone in Fahrenheit
#
# @return [String]
#
# @example
# Faker::Drone.operating_temperature #=> "14-104F"
#
# @faker.version 2.14.0
def operating_temperature
parse('drone.operating_temperature')
end
##
# Returns the drone battery capacity
#
# @return [String]
#
# @example
# Faker::Drone.battery_capacity #=> "3500 mAh"
#
# @faker.version 2.14.0
def battery_capacity
parse('drone.battery_capacity')
end
##
# Returns battery voltage
#
# @return [String]
#
# @example
# Faker::Drone.battery_voltage #=> "13.2V"
#
# @faker.version 2.14.0
def battery_voltage
parse('drone.battery_voltage')
end
##
# Returns the battery type
#
# @return [String]
#
# @example
# Faker::Drone.battery_type #=> "LiPo 4S"
#
# @faker.version 2.14.0
def battery_type
parse('drone.battery_type')
end
##
# Returns total battery weight in grams
#
# @return [String]
#
# @example
# Faker::Drone.battery_weight #=> "198 g"
#
# @faker.version 2.14.0
def battery_weight
parse('drone.battery_weight')
end
##
# Returns charging temperature for battery in Fahrenheit
#
# @return [String]
#
# @example
# Faker::Drone.charging_temperature #=> "41-104F"
#
# @faker.version 2.14.0
def charging_temperature
parse('drone.charging_temperature')
end
##
# Returns max chargin power required for battery
#
# @return [String]
#
# @example
# Faker::Drone.max_charging_power #=> "38W"
#
# @faker.version 2.14.0
def max_charging_power
parse('drone.max_charging_power')
end
##
# Returns camera ISO range for drone
#
# @return [String]
#
# @example
# Faker::Drone.iso #=> "100-3200"
#
# @faker.version 2.14.0
def iso
parse('drone.iso')
end
##
# Returns max camera resolution in MP"
#
# @return [String]
#
# @example
# Faker::Drone.max_resolution #=> "48MP"
#
# @faker.version 2.14.0
def max_resolution
parse('drone.max_resolution')
end
##
# Returns photo format for drone
#
# @return [String]
#
# @example
# Faker::Drone.photo_format #=> "JPEG"
#
# @faker.version 2.14.0
def photo_format
parse('drone.photo_format')
end
##
# Returns video format
#
# @return [String]
#
# @example
# Faker::Drone.video_format #=> "MP4"
#
# @faker.version 2.14.0
def video_format
parse('drone.video_format')
end
##
# Returns max and min shutter speed for camera
#
# @return [String]
#
# @example
# Faker::Drone.shutter_speed_range #=> "8-1/8000s"
#
# @faker.version 2.14.0
def shutter_speed_range
"#{fetch('drone.max_shutter_speed')}-#{fetch('drone.min_shutter_speed')}#{fetch('drone.shutter_speed_units')}"
end
##
# Returns max shutter speed for camera
#
# @return [String]
#
# @example
# Faker::Drone.max_shutter_speed #=> "60s"
#
# @faker.version 2.14.0
def max_shutter_speed
"#{fetch('drone.max_shutter_speed')}#{fetch('drone.shutter_speed_units')}"
end
##
# Returns min shutter speed for camera
#
# @return [String]
#
# @example
# Faker::Drone.min_shutter_speed #=> "1/8000s"
#
# @faker.version 2.14.0
def min_shutter_speed
"#{fetch('drone.min_shutter_speed')}#{fetch('drone.shutter_speed_units')}"
end
end
end
end
| ruby | MIT | a4d5e503edda970fc085e942018ee235622bfb11 | 2026-01-04T15:37:50.353881Z | false |
faker-ruby/faker | https://github.com/faker-ruby/faker/blob/a4d5e503edda970fc085e942018ee235622bfb11/lib/faker/default/compass.rb | lib/faker/default/compass.rb | # frozen_string_literal: true
module Faker
class Compass < Base
class << self
##
# Produces a random cardinal.
#
# @return [String]
#
# @example
# Faker::Compass.cardinal #=> "north"
#
# @faker.version 1.8.0
def cardinal
fetch('compass.cardinal.word')
end
##
# Produces a random ordinal.
#
# @return [String]
#
# @example
# Faker::Compass.ordinal #=> "northwest"
#
# @faker.version 1.8.0
def ordinal
fetch('compass.ordinal.word')
end
##
# Produces a random half wind.
#
# @return [String]
#
# @example
# Faker::Compass.half_wind #=> "north-northwest"
#
# @faker.version 1.8.0
def half_wind
fetch('compass.half-wind.word')
end
##
# Produces a random quarter wind.
#
# @return [String]
#
# @example
# Faker::Compass.quarter_wind #=> "north by west"
#
# @faker.version 1.8.0
def quarter_wind
fetch('compass.quarter-wind.word')
end
##
# Produces a random direction.
#
# @return [String]
#
# @example
# Faker::Compass.direction #=> "southeast"
#
# @faker.version 1.8.0
def direction
parse('compass.direction')
end
##
# Produces a random abbreviation.
#
# @return [String]
#
# @example
# Faker::Compass.abbreviation #=> "NEbN"
#
# @faker.version 1.8.0
def abbreviation
parse('compass.abbreviation')
end
##
# Produces a random azimuth.
#
# @return [String]
#
# @example
# Faker::Compass.azimuth #=> "168.75"
#
# @faker.version 1.8.0
def azimuth
parse('compass.azimuth')
end
##
# Produces a random cardinal abbreviation.
#
# @return [String]
#
# @example
# Faker::Compass.cardinal_abbreviation #=> "N"
#
# @faker.version 1.8.0
def cardinal_abbreviation
fetch('compass.cardinal.abbreviation')
end
##
# Produces a random ordinal abbreviation.
#
# @return [String]
#
# @example
# Faker::Compass.ordinal_abbreviation #=> "SW"
#
# @faker.version 1.8.0
def ordinal_abbreviation
fetch('compass.ordinal.abbreviation')
end
##
# Produces a random half wind abbreviation.
#
# @return [String]
#
# @example
# Faker::Compass.half_wind_abbreviation #=> "NNE"
#
# @faker.version 1.8.0
def half_wind_abbreviation
fetch('compass.half-wind.abbreviation')
end
##
# Produces a random quarter wind abbreviation.
#
# @return [String]
#
# @example
# Faker::Compass.quarter_wind_abbreviation #=> "SWbS"
#
# @faker.version 1.8.0
def quarter_wind_abbreviation
fetch('compass.quarter-wind.abbreviation')
end
##
# Produces a random cardinal azimuth.
#
# @return [String]
#
# @example
# Faker::Compass.cardinal_azimuth #=> "90"
#
# @faker.version 1.8.0
def cardinal_azimuth
fetch('compass.cardinal.azimuth')
end
##
# Produces a random ordinal azimuth.
#
# @return [String]
#
# @example
# Faker::Compass.ordinal_azimuth #=> "135"
#
# @faker.version 1.8.0
def ordinal_azimuth
fetch('compass.ordinal.azimuth')
end
##
# Produces a random half wind azimuth.
#
# @return [String]
#
# @example
# Faker::Compass.half_wind_azimuth #=> "292.5"
#
# @faker.version 1.8.0
def half_wind_azimuth
fetch('compass.half-wind.azimuth')
end
##
# Produces a random quarter wind azimuth
#
# @return [String]
#
# @example
# Faker::Compass.quarter_wind_azimuth #=> "56.25"
#
# @faker.version 1.8.0
def quarter_wind_azimuth
fetch('compass.quarter-wind.azimuth')
end
end
end
end
| ruby | MIT | a4d5e503edda970fc085e942018ee235622bfb11 | 2026-01-04T15:37:50.353881Z | false |
faker-ruby/faker | https://github.com/faker-ruby/faker/blob/a4d5e503edda970fc085e942018ee235622bfb11/lib/faker/default/source.rb | lib/faker/default/source.rb | # frozen_string_literal: true
module Faker
class Source < Base
class << self
##
# Produces source code for Hello World in a given language.
#
# @param lang [Symbol] The programming language to use
# @return [String]
#
# @example
# Faker::Source.hello_world #=> "puts 'Hello World!'"
#
# @example
# Faker::Source.hello_world(lang: :javascript)
# #=> "alert('Hello World!');"
#
# @faker.version 1.9.0
def hello_world(lang: :ruby)
fetch("source.hello_world.#{lang}")
end
##
# Produces source code for printing a string in a given language.
#
# @param str [String] The string to print
# @param lang [Symbol] The programming language to use
# @return [String]
#
# @example
# Faker::Source.print #=> "puts 'faker_string_to_print'"
# @example
# Faker::Source.print(str: 'foo bar', lang: :javascript)
# #=> "console.log('foo bar');"
#
# @faker.version 1.9.0
def print(str: 'some string', lang: :ruby)
code = fetch("source.print.#{lang}")
code.gsub('faker_string_to_print', str)
end
##
# Produces source code for printing 1 through 10 in a given language.
#
# @param lang [Symbol] The programming language to use
# @return [String]
#
# @example
# Faker::Source.print_1_to_10 #=> "(1..10).each { |i| puts i }"
# @example
# Faker::Source.print_1_to_10(lang: :javascript)
# # => "for (let i=0; i<10; i++) {
# # console.log(i);
# # }"
#
# @faker.version 1.9.0
def print_1_to_10(lang: :ruby)
fetch("source.print_1_to_10.#{lang}")
end
end
end
end
| ruby | MIT | a4d5e503edda970fc085e942018ee235622bfb11 | 2026-01-04T15:37:50.353881Z | false |
faker-ruby/faker | https://github.com/faker-ruby/faker/blob/a4d5e503edda970fc085e942018ee235622bfb11/lib/faker/default/programming_language.rb | lib/faker/default/programming_language.rb | # frozen_string_literal: true
module Faker
class ProgrammingLanguage < Base
class << self
##
# Produces the name of a programming language.
#
# @return [String]
#
# @example
# Faker::ProgrammingLanguage.name #=> "Ruby"
#
# @faker.version 1.8.5
def name
fetch('programming_language.name')
end
##
# Produces the name of a programming language's creator.
#
# @return [String]
#
# @example
# Faker::ProgrammingLanguage.creator #=> "Yukihiro Matsumoto"
#
# @faker.version 1.8.5
def creator
fetch('programming_language.creator')
end
end
end
end
| ruby | MIT | a4d5e503edda970fc085e942018ee235622bfb11 | 2026-01-04T15:37:50.353881Z | false |
faker-ruby/faker | https://github.com/faker-ruby/faker/blob/a4d5e503edda970fc085e942018ee235622bfb11/lib/faker/default/construction.rb | lib/faker/default/construction.rb | # frozen_string_literal: true
module Faker
class Construction < Base
##
# Produces a random material.
#
# @return [String]
#
# @example
# Faker::Construction.material #=> "Wood"
#
# @faker.version 1.9.2
def self.material
fetch('construction.materials')
end
##
# Produces a random heavy equipment.
#
# @return [String]
#
# @example
# Faker::Construction.heavy_equipment #=> "Excavator"
#
# @faker.version 1.9.2
def self.heavy_equipment
fetch('construction.heavy_equipment')
end
##
# Produces a random trade.
#
# @return [String]
#
# @example
# Faker::Construction.trade #=> "Carpenter"
#
# @faker.version 1.9.2
def self.trade
fetch('construction.trades')
end
##
# Produces a random subcontract category.
#
# @return [String]
#
# @example
# Faker::Construction.subcontract_category #=> "Curb & Gutter"
#
# @faker.version 1.9.2
def self.subcontract_category
fetch('construction.subcontract_categories')
end
##
# Produces a random standard cost code.
#
# @return [String]
#
# @example
# Faker::Construction.standard_cost_code #=> "1-000 - Purpose"
#
# @faker.version 1.9.2
def self.standard_cost_code
fetch('construction.standard_cost_codes')
end
##
# Produces a random role.
#
# @return [String]
#
# @example
# Faker::Construction.role #=> "Engineer"
#
# @faker.version 1.9.2
def self.role
fetch('construction.roles')
end
end
end
| ruby | MIT | a4d5e503edda970fc085e942018ee235622bfb11 | 2026-01-04T15:37:50.353881Z | false |
faker-ruby/faker | https://github.com/faker-ruby/faker/blob/a4d5e503edda970fc085e942018ee235622bfb11/lib/faker/default/measurement.rb | lib/faker/default/measurement.rb | # frozen_string_literal: true
module Faker
class Measurement < Base
class << self
ALL = 'all'
NONE = 'none'
##
# Produces a random height measurement.
#
# @param amount [Integer] Specifies the random height value.
# @return [String]
#
# @example
# Faker::Measurement.height #=> "6 inches"
# Faker::Measurement.height(amount: 1.4) #=> "1.4 inches"
# Faker::Measurement.height(amount: "none") #=> "inch"
# Faker::Measurement.height(amount: "all") #=> "inches"
#
# @faker.version 1.7.3
def height(amount: rand(10))
define_measurement_locale(amount, 'height')
end
##
# Produces a random length measurement.
#
# @param amount [Integer] Specifies the random length value.
# @return [String]
#
# @example
# Faker::Measurement.length #=> "1 yard"
# Faker::Measurement.length(amount: 1.4) #=> "1.4 yards"
#
# @faker.version 1.7.3
def length(amount: rand(10))
define_measurement_locale(amount, 'length')
end
##
# Produces a random volume measurement.
#
# @param amount [Integer] Specifies the random volume value.
# @return [String]
#
# @example
# Faker::Measurement.volume #=> "10 cups"
# Faker::Measurement.volume(amount: 1.4) #=> "1.4 cups"
#
# @faker.version 1.7.3
def volume(amount: rand(10))
define_measurement_locale(amount, 'volume')
end
##
# Produces a random weight measurement.
#
# @param amount [Integer] Specifies the random weight value.
# @return [String]
#
# @example
# Faker::Measurement.weight #=> "3 pounds"
# Faker::Measurement.weight(amount: 1.4) #=> "1.4 pounds"
#
# @faker.version 1.7.3
def weight(amount: rand(10))
define_measurement_locale(amount, 'weight')
end
##
# Produces a random metric height measurement.
#
# @param amount [Integer] Specifies the random height value.
# @return [String]
#
# @example
# Faker::Measurement.metric_height #=> "2 meters"
# Faker::Measurement.metric_height(amount: 1.4) #=> "1.4 meters"
#
# @faker.version 1.7.3
def metric_height(amount: rand(10))
define_measurement_locale(amount, 'metric_height')
end
##
# Produces a random metric length measurement.
#
# @param amount [Integer] Specifies the random length value.
# @return [String]
#
# @example
# Faker::Measurement.metric_length #=> "0 decimeters"
# Faker::Measurement.metric_length(amount: 1.4) #=> "1.4 decimeters"
#
# @faker.version 1.7.3
def metric_length(amount: rand(10))
define_measurement_locale(amount, 'metric_length')
end
##
# Produces a random metric volume measurement.
#
# @param amount [Integer] Specifies the random volume value.
# @return [String]
#
# @example
# Faker::Measurement.metric_volume #=> "1 liter"
# Faker::Measurement.metric_volume(amount: 1.4) #=> "1.4 liters"
#
# @faker.version 1.7.3
def metric_volume(amount: rand(10))
define_measurement_locale(amount, 'metric_volume')
end
##
# Produces a random metric weight measurement.
#
# @param amount [Integer] Specifies the random weight value.
# @return [String]
#
# @example
# Faker::Measurement.metric_weight #=> "8 grams"
# Faker::Measurement.metric_weight(amount: 1.4) #=> "1.4 grams"
#
# @faker.version 1.7.3
def metric_weight(amount: rand(10))
define_measurement_locale(amount, 'metric_weight')
end
private
def check_for_plural(text, number)
if number && number != 1
make_plural(text)
else
text
end
end
def define_measurement_locale(amount, locale)
ensure_valid_amount(amount)
case amount
when ALL
make_plural(fetch("measurement.#{locale}"))
when NONE
fetch("measurement.#{locale}")
else
locale = check_for_plural(fetch("measurement.#{locale}"), amount)
"#{amount} #{locale}"
end
end
def ensure_valid_amount(amount)
raise ArgumentError, 'invalid amount' unless amount == NONE || amount == ALL || amount.is_a?(Integer) || amount.is_a?(Float)
end
def make_plural(text)
case text
when 'foot'
'feet'
when 'inch'
'inches'
when 'fluid ounce'
'fluid ounces'
when 'metric ton'
'metric tons'
else
"#{text}s"
end
end
end
end
end
| ruby | MIT | a4d5e503edda970fc085e942018ee235622bfb11 | 2026-01-04T15:37:50.353881Z | false |
faker-ruby/faker | https://github.com/faker-ruby/faker/blob/a4d5e503edda970fc085e942018ee235622bfb11/lib/faker/default/kpop.rb | lib/faker/default/kpop.rb | # frozen_string_literal: true
module Faker
class Kpop < Base
class << self
##
# Produces the name of a 1990's 'OG' K-Pop group.
#
# @return [String]
#
# @example
# Faker::Kpop.i_groups #=> "Seo Taiji and Boys"
#
# @faker.version 1.8.5
def i_groups
fetch('kpop.i_groups')
end
##
# Produces the name of a 2000's K-Pop group.
#
# @return [String]
#
# @example
# Faker::Kpop.ii_groups #=> "Girls' Generation"
#
# @faker.version 1.8.5
def ii_groups
fetch('kpop.ii_groups')
end
##
# Produces the name of a 2010's K-Pop group.
#
# @return [String]
#
# @example
# Faker::Kpop.iii_groups #=> "Trouble Maker"
#
# @faker.version 1.8.5
def iii_groups
fetch('kpop.iii_groups')
end
##
# Produces the name of a K-Pop girl group.
#
# @return [String]
#
# @example
# Faker::Kpop.girl_groups #=> "2NE1"
#
# @faker.version 1.8.5
def girl_groups
fetch('kpop.girl_groups')
end
##
# Produces the name of a K-Pop boy band.
#
# @return [String]
#
# @example
# Faker::Kpop.boy_bands #=> "Exo"
#
# @faker.version 1.8.5
def boy_bands
fetch('kpop.boy_bands')
end
##
# Produces the name of a solo K-Pop artist.
#
# @return [String]
#
# @example
# Faker::Kpop.solo #=> "T.O.P"
#
# @faker.version 1.8.5
def solo
fetch('kpop.solo')
end
end
end
end
| ruby | MIT | a4d5e503edda970fc085e942018ee235622bfb11 | 2026-01-04T15:37:50.353881Z | false |
faker-ruby/faker | https://github.com/faker-ruby/faker/blob/a4d5e503edda970fc085e942018ee235622bfb11/lib/faker/default/artist.rb | lib/faker/default/artist.rb | # frozen_string_literal: true
module Faker
class Artist < Base
class << self
##
# Produces the name of an artist.
#
# @return [String]
#
# @example
# Faker::Artist.name #=> "Michelangelo"
#
# @faker.version 1.8.8
def name
fetch('artist.names')
end
end
end
end
| ruby | MIT | a4d5e503edda970fc085e942018ee235622bfb11 | 2026-01-04T15:37:50.353881Z | false |
faker-ruby/faker | https://github.com/faker-ruby/faker/blob/a4d5e503edda970fc085e942018ee235622bfb11/lib/faker/default/superhero.rb | lib/faker/default/superhero.rb | # frozen_string_literal: true
module Faker
class Superhero < Base
class << self
##
# Produces a superpower.
#
# @return [String]
#
# @example
# Faker::Superhero.power #=> "Photokinesis"
#
# @faker.version 1.6.2
def power
fetch('superhero.power')
end
##
# Produces a superhero name prefix.
#
# @return [String]
#
# @example
# Faker::Superhero.prefix #=> "the Fated"
#
# @faker.version 1.6.2
def prefix
fetch('superhero.prefix')
end
##
# Produces a superhero name suffix.
#
# @return [String]
#
# @example
# Faker::Superhero.suffix #=> "Captain"
#
# @faker.version 1.6.2
def suffix
fetch('superhero.suffix')
end
##
# Produces a superhero descriptor.
#
# @return [String]
#
# @example
# Faker::Superhero.descriptor #=> "Bizarro"
#
# @faker.version 1.6.2
def descriptor
fetch('superhero.descriptor')
end
##
# Produces a random superhero name.
#
# @return [String]
#
# @example
# Faker::Superhero.name #=> "Magnificent Shatterstar"
#
# @faker.version 1.6.2
def name
parse('superhero.name')
end
end
end
end
| ruby | MIT | a4d5e503edda970fc085e942018ee235622bfb11 | 2026-01-04T15:37:50.353881Z | false |
faker-ruby/faker | https://github.com/faker-ruby/faker/blob/a4d5e503edda970fc085e942018ee235622bfb11/lib/faker/default/world_cup.rb | lib/faker/default/world_cup.rb | # frozen_string_literal: true
module Faker
class WorldCup < Base
class << self
##
# Produces a national team name.
#
# @return [String]
#
# @example
# Faker::WorldCup.team #=> "Iran"
#
# @faker.version 1.9.0
def team
fetch('world_cup.teams')
end
##
# Produces a city name hosting the World Cup match.
#
# @return [String]
#
# @example
# Faker::WorldCup.city #=> "Moscow"
#
# @faker.version 2.13.0
def city
fetch('world_cup.cities')
end
##
# Produces the name of a stadium that has hosted a World Cup match.
#
# @return [String]
#
# @example
# Faker::WorldCup.stadium #=> "Rostov Arena"
#
# @faker.version 2.13.0
def stadium
fetch('world_cup.stadiums')
end
##
# Produces a random national team name from a group.
#
# @return [String]
#
# @example
# Faker::WorldCup.group(group: 'group_B') #=> "Spain"
# @example
# Faker::WorldCup.group #=> "Russia"
#
# @faker.version 2.13.0
def group(group: 'group_A')
fetch("world_cup.groups.#{group}")
end
##
# Produces a random name from national team roster.
#
# @return [String]
#
# @example
# Faker::WorldCup.roster #=> "Hector Cuper"
#
# @example
# Faker::WorldCup.roster(country: 'Spain', type: 'forwards') #=> "Diego Costa"
#
# @faker.version 2.13.0
def roster(country: 'Egypt', type: 'coach')
fetch("world_cup.rosters.#{country}.#{type}")
end
end
end
end
| ruby | MIT | a4d5e503edda970fc085e942018ee235622bfb11 | 2026-01-04T15:37:50.353881Z | false |
faker-ruby/faker | https://github.com/faker-ruby/faker/blob/a4d5e503edda970fc085e942018ee235622bfb11/lib/faker/default/emotion.rb | lib/faker/default/emotion.rb | # frozen_string_literal: true
module Faker
class Emotion < Base
class << self
##
# Produces an emotion noun.
#
# @return [String]
#
# @example
# Faker::Emotion.noun #=> "amazement"
#
# @faker.version next
def noun
fetch('emotion.noun')
end
##
# Produces an emotion adjective.
#
# @return [String]
#
# @example
# Faker::Emotion.adjective # => "nonplussed"
#
# @faker.version next
def adjective
fetch('emotion.adjective')
end
end
end
end
| ruby | MIT | a4d5e503edda970fc085e942018ee235622bfb11 | 2026-01-04T15:37:50.353881Z | false |
faker-ruby/faker | https://github.com/faker-ruby/faker/blob/a4d5e503edda970fc085e942018ee235622bfb11/lib/faker/default/cannabis.rb | lib/faker/default/cannabis.rb | # frozen_string_literal: true
module Faker
class Cannabis < Base
##
# Produces a random strain.
#
# @return [String]
#
# @example
# Faker::Cannabis.strain #=> "Super Glue"
#
# @faker.version 1.9.1
def self.strain
fetch('cannabis.strains')
end
##
# Produces a random abbreviation.
#
# @return [String]
#
# @example
# Faker::Cannabis.cannabinoid_abbreviation #=> "CBGa"
#
# @faker.version 1.9.1
def self.cannabinoid_abbreviation
fetch('cannabis.cannabinoid_abbreviations')
end
##
# Produces a random cannabinoid type.
#
# @return [String]
#
# @example
# Faker::Cannabis.cannabinoid #=> "Cannabinolic Acid"
#
# @faker.version 1.9.1
def self.cannabinoid
fetch('cannabis.cannabinoids')
end
##
# Produces a random terpene type.
#
# @return [String]
#
# @example
# Faker::Cannabis.terpene #=> "Terpinene"
#
# @faker.version 1.9.1
def self.terpene
fetch('cannabis.terpenes')
end
##
# Produces a random kind of medical use.
#
# @return [String]
#
# @example
# Faker::Cannabis.medical_use #=> "anti-cancer"
#
# @faker.version 1.9.1
def self.medical_use
fetch('cannabis.medical_uses')
end
##
# Produces a random health benefit.
#
# @return [String]
#
# @example
# Faker::Cannabis.health_benefit #=> "prevents infection"
#
# @faker.version 1.9.1
def self.health_benefit
fetch('cannabis.health_benefits')
end
##
# Produces a random category.
#
# @return [String]
#
# @example
# Faker::Cannabis.category #=> "crystalline"
#
# @faker.version 1.9.1
def self.category
fetch('cannabis.categories')
end
##
# Produces a random type.
#
# @return [String]
#
# @example
# Faker::Cannabis.type #=> "indica"
#
# @faker.version 1.9.1
def self.type
fetch('cannabis.types')
end
##
# Produces a random buzzword.
#
# @return [String]
#
# @example
# Faker::Cannabis.buzzword #=> "high"
#
# @faker.version 1.9.1
def self.buzzword
fetch('cannabis.buzzwords')
end
##
# Produces a random brand.
#
# @return [String]
#
# @example
# Faker::Cannabis.brand #=> "Cannavore Confections"
#
# @faker.version 1.9.1
def self.brand
fetch('cannabis.brands')
end
end
end
| ruby | MIT | a4d5e503edda970fc085e942018ee235622bfb11 | 2026-01-04T15:37:50.353881Z | false |
faker-ruby/faker | https://github.com/faker-ruby/faker/blob/a4d5e503edda970fc085e942018ee235622bfb11/lib/faker/default/vulnerability_identifier.rb | lib/faker/default/vulnerability_identifier.rb | # frozen_string_literal: true
module Faker
class VulnerabilityIdentifier < Base
class << self
##
# Produces a Common Vulnerabilities and Exposures (CVE) identifier.
#
# @param year [Integer] The year-part of the CVE identifier (defaults to the current year)
# @return [String]
#
# @example
# Faker::VulnerabilityIdentifier.cve #=> "CVE-2021-1337"
# Faker::VulnerabilityIdentifier.cve(year: 1999) #=> "CVE-1999-0523"
#
# @faker.version next
def cve(year: ::Date.today.year)
index = rand_in_range(1, 99_999).to_s.rjust(4, '0')
"CVE-#{year}-#{index}"
end
end
end
end
| ruby | MIT | a4d5e503edda970fc085e942018ee235622bfb11 | 2026-01-04T15:37:50.353881Z | false |
faker-ruby/faker | https://github.com/faker-ruby/faker/blob/a4d5e503edda970fc085e942018ee235622bfb11/lib/faker/default/beer.rb | lib/faker/default/beer.rb | # frozen_string_literal: true
module Faker
class Beer < Base
flexible :beer
class << self
##
# Produces a random beer name.
#
# @return [String]
#
# @example
# Faker::Beer.name #=> "Pliny The Elder"
#
# @faker.version 1.6.2
def name
fetch('beer.name')
end
##
# Produces a random beer style.
#
# @return [String]
#
# @example
# Faker::Beer.style #=> "Wood-aged Beer"
#
# @faker.version 1.6.2
def style
fetch('beer.style')
end
##
# Produces a random beer hops.
#
# @return [String]
#
# @example
# Faker::Beer.hop #=> "Sterling"
#
# @faker.version 1.6.2
def hop
fetch('beer.hop')
end
##
# Produces a random beer yeast.
#
# @return [String]
#
# @example
# Faker::Beer.yeast #=> "5335 - Lactobacillus"
#
# @faker.version 1.6.2
def yeast
fetch('beer.yeast')
end
##
# Produces a random beer malt.
#
# @return [String]
#
# @example
# Faker::Beer.malts #=> "Munich"
#
# @faker.version 1.6.2
def malts
fetch('beer.malt')
end
##
# Produces a random beer IBU.
#
# @return [String]
#
# @example
# Faker::Beer.ibu #=> "87 IBU"
#
# @faker.version 1.6.2
def ibu
"#{rand(10..100)} IBU"
end
##
# Produces a random beer alcohol percentage.
#
# @return [String]
#
# @example
# Faker::Beer.alcohol #=> "5.4%"
#
# @faker.version 1.6.2
def alcohol
"#{rand(2.0..10.0).round(1)}%"
end
##
# Produces a random beer blg level.
#
# @return [String]
#
# @example
# Faker::Beer.blg #=> "5.1Blg"
#
# @faker.version 1.6.2
def blg
"#{rand(5.0..20.0).round(1)}°Blg"
end
end
end
end
| ruby | MIT | a4d5e503edda970fc085e942018ee235622bfb11 | 2026-01-04T15:37:50.353881Z | false |
faker-ruby/faker | https://github.com/faker-ruby/faker/blob/a4d5e503edda970fc085e942018ee235622bfb11/lib/faker/default/dessert.rb | lib/faker/default/dessert.rb | # frozen_string_literal: true
module Faker
class Dessert < Base
flexible :dessert
class << self
##
# Produces the name of a dessert variety.
#
# @return [String]
#
# @example
# Faker::Dessert.variety #=> "Cake"
#
# @faker.version 1.8.0
def variety
fetch('dessert.variety')
end
##
# Produces the name of a dessert topping.
#
# @return [String]
#
# @example
# Faker::Dessert.topping #=> "Gummy Bears"
#
# @faker.version 1.8.0
def topping
fetch('dessert.topping')
end
##
# Produces the name of a dessert flavor.
#
# @return [String]
#
# @example
# Faker::Dessert.flavor #=> "Salted Caramel"
#
# @faker.version 1.8.0
def flavor
fetch('dessert.flavor')
end
end
end
end
| ruby | MIT | a4d5e503edda970fc085e942018ee235622bfb11 | 2026-01-04T15:37:50.353881Z | false |
faker-ruby/faker | https://github.com/faker-ruby/faker/blob/a4d5e503edda970fc085e942018ee235622bfb11/lib/faker/default/science.rb | lib/faker/default/science.rb | # frozen_string_literal: true
module Faker
class Science < Base
class << self
BRANCHES = {
empirical: %i[empirical_natural_basic empirical_natural_applied empirical_social_basic empirical_social_applied],
formal: %i[formal_basic formal_applied],
natural: %i[empirical_natural_basic empirical_natural_applied],
social: %i[empirical_social_basic empirical_social_applied],
basic: %i[empirical_natural_basic empirical_social_basic formal_basic],
applied: %i[empirical_natural_applied empirical_social_applied formal_applied]
}.freeze
##
# Produces a name of a science
# You can optionally filter by specifying one or more of the following:
# `:empirical, :formal, :natural, :social, :basic, :applied`
# @see https://en.wikipedia.org/wiki/Science#Branches_of_science
# @see Faker::Educator.subject
#
# @param branches [Array<Symbol>]
# @return [String]
#
# @example
# Faker::Science.science #=> "Space science"
# Faker::Science.science(:natural, :applied) #=> "Engineering"
# Faker::Science.science(:formal, :applied) #=> "Computer Science"
#
# @faker.version next
def science(*branches)
selected = BRANCHES.values.flatten.uniq
branches.each do |branch|
selected &= BRANCHES[branch] if BRANCHES.key? branch
end
raise ArgumentError, 'Filters do not match any sciences' if selected.empty?
sciences = []
selected.each do |branch|
sciences += translate("faker.science.branch.#{branch}")
end
sample(sciences)
end
##
# Produces the name of a element.
#
# @return [String]
#
# @example
# Faker::Science.element #=> "Carbon"
#
# @faker.version 1.8.5
def element
fetch('science.element')
end
##
# Produces the symbol of an element.
#
# @return [String]
#
# @example
# Faker::Science.element_symbol #=> "Pb"
#
# @faker.version 1.9.0
def element_symbol
fetch('science.element_symbol')
end
##
# Produces the state of an element.
#
# @return [String]
#
# @example
# Faker::Science.element_state #=> "Liquid"
#
# @faker.version next
def element_state
fetch('science.element_state')
end
##
# Produces the subcategory of an element.
#
# @return [String]
#
# @example
# Faker::Science.element_subcategory #=> "Reactive nonmetal"
#
# @faker.version next
def element_subcategory
fetch('science.element_subcategory')
end
##
# Produces the name of a scientist.
#
# @return [String]
#
# @example
# Faker::Science.scientist #=> "Isaac Newton"
#
# @faker.version 1.8.5
def scientist
fetch('science.scientist')
end
##
# Produces a scientifically sounding word
#
# @return [String]
#
# @example
# Faker::Science.modifier #=> "Quantum"
# Faker::Science.modifier #=> "Superconductive"
#
# @faker.version next
def modifier
fetch('science.modifier')
end
##
# Produces the name of a scientific tool.
# By default it uses a science word modifier to generate more diverse data, which can be disabled.
#
# @param simple [Boolean] Whether to generate simple realistic tool names, (no Q-word).
# @return [String]
#
# @example
# Faker::Science.tool #=> "Superconductive Microcentrifuge"
# Faker::Science.tool #=> "Portable Cryostat"
# Faker::Science.tool #=> "Quantum Spectrophotometer"
# Faker::Science.tool(simple: true) #=> "Microcentrifuge"
#
# @faker.version next
def tool(simple: false)
tool = fetch('science.tool')
return tool if simple
# Makes sure the modifier are different
loop do
modifier = self.modifier
break unless tool.start_with?(modifier)
end
"#{modifier} #{tool}"
end
end
end
end
| ruby | MIT | a4d5e503edda970fc085e942018ee235622bfb11 | 2026-01-04T15:37:50.353881Z | false |
faker-ruby/faker | https://github.com/faker-ruby/faker/blob/a4d5e503edda970fc085e942018ee235622bfb11/lib/faker/default/placeholdit.rb | lib/faker/default/placeholdit.rb | # frozen_string_literal: true
module Faker
class Placeholdit < Base
class << self
SUPPORTED_FORMATS = %w[png jpg gif jpeg].freeze
##
# Produces a random placeholder image from https://via.placeholder.com.
#
# @param size [String] Specifies the image's size, dimensions separated by 'x'.
# @param format [String] Specifies the image's extension.
# @param background_color [String, Symbol] Specifies the background color, either in hexadecimal format (without #) or as :random.
# @param text_color [String, Symbol] Specifies the text color, either in hexadecimal format (without #) or as :random.
# @param text [String] Specifies a custom text to be used.
# @return [String]
#
# @example
# # Keyword arguments: size, format, background_color, text_color, text
# Faker::Placeholdit.image #=> "https://via.placeholder.com/300x300.png"
# Faker::Placeholdit.image(size: '50x50') #=> "https://via.placeholder.com/50x50.png"
# Faker::Placeholdit.image(size: '50x50', format: 'jpg') #=> "https://via.placeholder.com/50x50.jpg"
# Faker::Placeholdit.image(size: '50x50', format: 'gif', background_color: 'ffffff') #=> "https://via.placeholder.com/50x50.gif/ffffff"
# Faker::Placeholdit.image(size: '50x50', format: 'jpeg', background_color: :random) #=> "https://via.placeholder.com/50x50.jpeg/39eba7"
# Faker::Placeholdit.image(size: '50x50', format: 'jpeg', background_color: 'ffffff', text_color: '000') #=> "https://via.placeholder.com/50x50.jpeg/ffffff/000"
# Faker::Placeholdit.image(size: '50x50', format: 'jpg', background_color: 'ffffff', text_color: '000', text: 'Some Custom Text') #=> "https://via.placeholder.com/50x50.jpg/ffffff/000?text=Some Custom Text"
#
# @faker.version 1.6.0
def image(size: '300x300', format: 'png', background_color: nil, text_color: nil, text: nil)
background_color = generate_color if background_color == :random
text_color = generate_color if text_color == :random
raise ArgumentError, 'Size should be specified in format 300x300' unless size =~ /^[0-9]+x[0-9]+$/
raise ArgumentError, "Supported formats are #{SUPPORTED_FORMATS.join(', ')}" unless SUPPORTED_FORMATS.include?(format)
raise ArgumentError, "background_color must be a hex value without '#'" unless background_color.nil? || background_color =~ /((?:^\h{3}$)|(?:^\h{6}$)){1}(?!.*\H)/
raise ArgumentError, "text_color must be a hex value without '#'" unless text_color.nil? || text_color =~ /((?:^\h{3}$)|(?:^\h{6}$)){1}(?!.*\H)/
image_url = "https://via.placeholder.com/#{size}.#{format}"
image_url += "/#{background_color}" if background_color
image_url += "/#{text_color}" if text_color
image_url += "?text=#{text}" if text
image_url
end
private
def generate_color
format('%06x', rand * 0xffffff)
end
end
end
end
| ruby | MIT | a4d5e503edda970fc085e942018ee235622bfb11 | 2026-01-04T15:37:50.353881Z | false |
faker-ruby/faker | https://github.com/faker-ruby/faker/blob/a4d5e503edda970fc085e942018ee235622bfb11/lib/faker/default/south_africa.rb | lib/faker/default/south_africa.rb | # frozen_string_literal: true
module Faker
class SouthAfrica < Base
class << self
##
# Produces a South African ID number.
#
# @return [String]
#
# @example
# Faker::SouthAfrica.id_number #=> "6110311856083"
#
# @faker.version 1.9.2
def id_number
Faker::IdNumber.south_african_id_number
end
##
# Produces a valid South African ID number
#
# @return [String]
#
# @example
# Faker::SouthAfrica.valid_id_number #=> "6110311856083"
#
# @faker.version 1.9.2
def valid_id_number
Faker::IdNumber.valid_south_african_id_number
end
##
# Produces an invalid South African ID number
#
# @return [String]
#
# @example
# Faker::SouthAfrica.invalid_id_number #=> "7018356904081"
#
# @faker.version 1.9.2
def invalid_id_number
Faker::IdNumber.invalid_south_african_id_number
end
##
# Produces a South African phone number.
#
# @return [String]
#
# @example
# Faker::SouthAfrica.phone_number #=> "010 788 5009"
#
# @faker.version 1.9.2
def phone_number
with_locale 'en-ZA' do
Faker::PhoneNumber.phone_number
end
end
##
# Produces a South African cell phone number.
#
# @return [String]
#
# @example
# Faker::SouthAfrica.cell_phone #=> "082 946 7470"
#
# @faker.version 1.9.2
def cell_phone
with_locale 'en-ZA' do
Faker::PhoneNumber.cell_phone
end
end
##
# Produces a South African private company registration number.
#
# @return [String]
#
# @example
# Faker::SouthAfrica.pty_ltd_registration_number #=> "5301/714689/07"
#
# @faker.version 1.9.2
def pty_ltd_registration_number
Faker::Company.south_african_pty_ltd_registration_number
end
##
# Produces a South African close corporation registration number.
#
# @return [String]
#
# @example
# Faker::SouthAfrica.close_corporation_registration_number #=> "CK74/7585/23"
#
# @faker.version 1.9.2
def close_corporation_registration_number
Faker::Company.south_african_close_corporation_registration_number
end
##
# Produces a South African listed company registration number.
#
# @return [String]
#
# @example
# Faker::SouthAfrica.listed_company_registration_number #=> "7039/3135/06"
#
# @faker.version 1.9.2
def listed_company_registration_number
Faker::Company.south_african_listed_company_registration_number
end
##
# Produces a South African trust registration number.
#
# @return [String]
#
# @example
# Faker::SouthAfrica.trust_registration_number #=> "IT38/6489900"
#
# @faker.version 1.9.2
def trust_registration_number
Faker::Company.south_african_trust_registration_number
end
##
# Produces a South African VAT number.
#
# @return [String]
#
# @example
# Faker::SouthAfrica.vat_number #=> "ZA79494416181"
#
# @faker.version 1.9.2
def vat_number
Faker::Finance.vat_number(country: 'ZA')
end
end
end
end
| ruby | MIT | a4d5e503edda970fc085e942018ee235622bfb11 | 2026-01-04T15:37:50.353881Z | false |
faker-ruby/faker | https://github.com/faker-ruby/faker/blob/a4d5e503edda970fc085e942018ee235622bfb11/lib/faker/default/relationship.rb | lib/faker/default/relationship.rb | # frozen_string_literal: true
module Faker
class Relationship < Base
flexible :relationship
class << self
##
# Produces a random family relationship.
#
# @return [String]
#
# @example
# Faker::Relationship.familial #=> "Grandfather"
#
# @faker.version 1.9.2
def familial(connection: nil)
familial_connections = translate('faker.relationship.familial').keys
if connection.nil?
connection = sample(familial_connections).to_s
else
connection = connection.to_s.downcase
unless familial_connections.include?(connection.to_sym)
raise ArgumentError,
"Familial connections can be left blank or #{familial_connections.join(', ')}"
end
end
fetch("relationship.familial.#{connection}")
end
##
# Produces a random in-law relationship.
#
# @return [String]
#
# @example
# Faker::Relationship.in_law #=> "Brother-in-law"
#
# @faker.version 1.9.2
def in_law
fetch('relationship.in_law')
end
##
# Produces a random spouse relationship.
#
# @return [String]
#
# @example
# Faker::Relationship.spouse #=> "Husband"
#
# @faker.version 1.9.2
def spouse
fetch('relationship.spouse')
end
##
# Produces a random parent relationship.
#
# @return [String]
#
# @example
# Faker::Relationship.parent #=> "Father"
#
# @faker.version 1.9.2
def parent
fetch('relationship.parent')
end
##
# Produces a random sibling relationship.
#
# @return [String]
#
# @example
# Faker::Relationship.sibling #=> "Sister"
#
# @faker.version 1.9.2
def sibling
fetch('relationship.sibling')
end
end
end
end
| ruby | MIT | a4d5e503edda970fc085e942018ee235622bfb11 | 2026-01-04T15:37:50.353881Z | false |
faker-ruby/faker | https://github.com/faker-ruby/faker/blob/a4d5e503edda970fc085e942018ee235622bfb11/lib/faker/default/internet_http.rb | lib/faker/default/internet_http.rb | # frozen_string_literal: true
module Faker
class Internet
class HTTP < Base
STATUS_CODES = {
information: [100, 101, 102, 103],
successful: [200, 201, 202, 203, 204, 205, 206, 207, 208, 226],
redirect: [300, 301, 302, 303, 304, 305, 306, 307, 308],
client_error: [400, 401, 402, 403, 404, 405, 406, 407, 408, 409, 410, 411, 412,
413, 414, 415, 416, 417, 418, 421, 422, 423, 424, 425, 426, 428,
429, 431, 451],
server_error: [500, 501, 502, 503, 504, 505, 506, 507, 508, 510, 511]
}.freeze
STATUS_CODES_GROUPS = STATUS_CODES.keys.freeze
class << self
##
# Produces an HTTP status code
#
# @return [Integer]
#
# @example
# Faker::Internet::HTTP.status_code #=> 418
# @example
# Faker::Internet::HTTP.status_code(group: :information) #=> 102
# @example
# Faker::Internet::HTTP.status_code(group: :successful) #=> 200
# @example
# Faker::Internet::HTTP.status_code(group: :redirect) #=> 306
# @example
# Faker::Internet::HTTP.status_code(group: :client_error) #=> 451
# @example
# Faker::Internet::HTTP.status_code(group: :server_error) #=> 502
#
# @faker.version 2.13.0
def status_code(group: nil)
return STATUS_CODES[STATUS_CODES_GROUPS.sample].sample unless group
raise ArgumentError, 'Invalid HTTP status code group' unless STATUS_CODES_GROUPS.include?(group)
STATUS_CODES[group].sample
end
end
end
end
end
| ruby | MIT | a4d5e503edda970fc085e942018ee235622bfb11 | 2026-01-04T15:37:50.353881Z | false |
faker-ruby/faker | https://github.com/faker-ruby/faker/blob/a4d5e503edda970fc085e942018ee235622bfb11/lib/faker/default/mountain.rb | lib/faker/default/mountain.rb | # frozen_string_literal: true
module Faker
class Mountain < Base
class << self
##
# Produces a name of a mountain
#
# @return [String]
#
# @example
# Faker::Mountain.name #=> "Mount Everest"
#
# @faker.version next
def name
fetch('mountain.name')
end
##
# Produces a name of a range
#
# @return [String]
#
# @example
# Faker::Mountain.range #=> "Dhaulagiri Himalaya"
#
# @faker.version next
def range
fetch('mountain.range')
end
end
end
end
| ruby | MIT | a4d5e503edda970fc085e942018ee235622bfb11 | 2026-01-04T15:37:50.353881Z | false |
faker-ruby/faker | https://github.com/faker-ruby/faker/blob/a4d5e503edda970fc085e942018ee235622bfb11/lib/faker/default/computer.rb | lib/faker/default/computer.rb | # frozen_string_literal: true
module Faker
class Computer < Base
class << self
##
# Produces the name of a computer platform.
#
# @return [String]
#
# @example
# Faker::Computer.platform #=> "Linux"
#
# @faker.version 2.12.0
def platform
fetch('computer.platform')
end
##
# Produces the name of a computer type.
#
# @return [String]
#
# @example
# Faker::Computer.type #=> "server"
#
# @faker.version 2.12.0
def type
fetch('computer.type')
end
##
# Produces the name of a computer os.
#
# @param platform [String] optionally specify the platform `linux`, `macos`, or `windows`.
# @return [String]
#
# @example
# Faker::Computer.os #=> "RHEL 6.10"
#
# @faker.version 2.12.0
def os(platform: self.platform)
platform = self.platform unless fetch_all('computer.platform').include?(platform)
fetch("computer.os.#{platform.downcase}")
end
##
# Produces a string with computer platform and os
#
# @return [String]
#
# @example
# Faker::Computer.stack #=> "Linux, RHEL 6.10"
#
# @faker.version 2.12.0
def stack
platform = self.platform
os = fetch("computer.os.#{platform.downcase}")
"#{platform}, #{os}"
end
end
end
end
| ruby | MIT | a4d5e503edda970fc085e942018ee235622bfb11 | 2026-01-04T15:37:50.353881Z | false |
faker-ruby/faker | https://github.com/faker-ruby/faker/blob/a4d5e503edda970fc085e942018ee235622bfb11/lib/faker/default/nato_phonetic_alphabet.rb | lib/faker/default/nato_phonetic_alphabet.rb | # frozen_string_literal: true
module Faker
class NatoPhoneticAlphabet < Base
class << self
##
# Produces a code word from the NATO phonetic alphabet.
#
# @return [String]
#
# @example
# Faker::NatoPhoneticAlphabet.code_word #=> "Hotel"
#
# @faker.version 1.9.0
def code_word
fetch('nato_phonetic_alphabet.code_word')
end
end
end
end
| ruby | MIT | a4d5e503edda970fc085e942018ee235622bfb11 | 2026-01-04T15:37:50.353881Z | false |
faker-ruby/faker | https://github.com/faker-ruby/faker/blob/a4d5e503edda970fc085e942018ee235622bfb11/lib/faker/default/business.rb | lib/faker/default/business.rb | # frozen_string_literal: true
require 'date'
module Faker
class Business < Base
flexible :business
class << self
##
# Produces a credit card number.
#
# @return [String]
#
# @example
# Faker::Business.credit_card_number #=> "1228-1221-1221-1431"
#
# @faker.version 1.2.0
def credit_card_number
fetch('business.credit_card_numbers')
end
##
# Produces a credit card expiration date.
#
# @return [Date]
#
# @example
# Faker::Business.credit_card_expiry_date #=> <Date: 2015-11-11 ((2457338j,0s,0n),+0s,2299161j)>
#
# @faker.version 1.2.0
def credit_card_expiry_date
::Date.today + (365 * rand(1..4))
end
##
# Produces a type of credit card.
#
# @return [String]
#
# @example
# Faker::Business.credit_card_type #=> "visa"
#
# @faker.version 1.2.0
def credit_card_type
fetch('business.credit_card_types')
end
end
end
end
| ruby | MIT | a4d5e503edda970fc085e942018ee235622bfb11 | 2026-01-04T15:37:50.353881Z | false |
faker-ruby/faker | https://github.com/faker-ruby/faker/blob/a4d5e503edda970fc085e942018ee235622bfb11/lib/faker/default/funny_name.rb | lib/faker/default/funny_name.rb | # frozen_string_literal: true
module Faker
class FunnyName < Base
flexible :funny_name
class << self
##
# Retrieves a funny name.
#
# @return [String]
#
# @example
# Faker::FunnyName.name #=> "Sam Pull"
#
# @faker.version 1.8.0
def name
fetch('funny_name.name')
end
##
# Retrieves a funny two word name.
#
# @return [String]
#
# @example
# Faker::FunnyName.two_word_name #=> "Shirley Knot"
#
# @faker.version 1.8.0
def two_word_name
two_word_names = fetch_all('funny_name.name').select do |name|
name.count(' ') == 1
end
sample(two_word_names)
end
##
# Retrieves a funny three word name.
#
# @return [String]
#
# @example
# Faker::FunnyName.three_word_name #=> "Carson O. Gin"
#
# @faker.version 1.8.0
def three_word_name
three_word_names = fetch_all('funny_name.name').select do |name|
name.count(' ') == 2
end
sample(three_word_names)
end
##
# Retrieves a funny four word name.
#
# @return [String]
#
# @example
# Faker::FunnyName.four_word_name #=> "Maude L. T. Ford"
#
# @faker.version 1.8.0
def four_word_name
four_word_names = fetch_all('funny_name.name').select do |name|
name.count(' ') == 3
end
sample(four_word_names)
end
##
# Retrieves a funny name with an initial.
#
# @return [String]
#
# @example
# Faker::FunnyName.name_with_initial #=> "Heather N. Yonn"
#
# @faker.version 1.8.0
def name_with_initial
names_with_initials = fetch_all('funny_name.name').select do |name|
name.count('.').positive?
end
sample(names_with_initials)
end
end
end
end
| ruby | MIT | a4d5e503edda970fc085e942018ee235622bfb11 | 2026-01-04T15:37:50.353881Z | false |
faker-ruby/faker | https://github.com/faker-ruby/faker/blob/a4d5e503edda970fc085e942018ee235622bfb11/lib/faker/default/restaurant.rb | lib/faker/default/restaurant.rb | # frozen_string_literal: true
module Faker
class Restaurant < Base
flexible :restaurant
class << self
##
# Produces the name of a restaurant.
#
# @return [String]
#
# @example
# Faker::Restaurant.name #=> "Curry King"
#
# @faker.version 1.9.2
def name
bothify(parse('restaurant.name'))
end
##
# Produces a type of restaurant.
#
# @return [String]
#
# @example
# Faker::Restaurant.type #=> "Comfort Food"
#
# @faker.version 1.9.2
def type
fetch('restaurant.type')
end
##
# Produces a description of a restaurant.
#
# @return [String]
#
# @example
# Faker::Restaurant.description
# #=> "We are committed to using the finest ingredients in our recipes. No food leaves our kitchen that we ourselves would not eat."
#
# @faker.version 1.9.2
def description
fetch('restaurant.description')
end
##
# Produces a review for a restaurant.
#
# @return [String]
#
# @example
# Faker::Restaurant.review
# #=> "Brand new. Great design. Odd to hear pop music in a Mexican establishment. Music is a bit loud. It should be background."
#
# @faker.version 1.9.2
def review
fetch('restaurant.review')
end
end
end
end
| ruby | MIT | a4d5e503edda970fc085e942018ee235622bfb11 | 2026-01-04T15:37:50.353881Z | false |
faker-ruby/faker | https://github.com/faker-ruby/faker/blob/a4d5e503edda970fc085e942018ee235622bfb11/lib/faker/default/dc_comics.rb | lib/faker/default/dc_comics.rb | # frozen_string_literal: true
module Faker
class DcComics < Base
##
# Produces a hero name from DC Comics
#
# @return [String]
#
# @example
# Faker::DcComics.hero #=> "Batman"
#
# @faker.version 1.9.2
def self.hero
fetch('dc_comics.hero')
end
##
# Produces a heroine name from DC Comics
#
# @return [String]
#
# @example
# Faker::DcComics.heroine #=> "Supergirl"
#
# @faker.version 1.9.2
def self.heroine
fetch('dc_comics.heroine')
end
##
# Produces a villain name from DC Comics
#
# @return [String]
#
# @example
# Faker::DcComics.villain #=> "The Joker"
#
# @faker.version 1.9.2
def self.villain
fetch('dc_comics.villain')
end
##
# Produces a character name from DC Comics
#
# @return [String]
#
# @example
# Faker::DcComics.name #=> "Clark Kent"
#
# @faker.version 1.9.2
def self.name
fetch('dc_comics.name')
end
##
# Produces a comic book title from DC Comics
#
# @return [String]
#
# @example
# Faker::DcComics.title #=> "Batman: The Long Halloween"
#
# @faker.version 1.9.2
def self.title
fetch('dc_comics.title')
end
end
end
| ruby | MIT | a4d5e503edda970fc085e942018ee235622bfb11 | 2026-01-04T15:37:50.353881Z | false |
faker-ruby/faker | https://github.com/faker-ruby/faker/blob/a4d5e503edda970fc085e942018ee235622bfb11/lib/faker/default/lorem_flickr.rb | lib/faker/default/lorem_flickr.rb | # frozen_string_literal: true
module Faker
class LoremFlickr < Base
class << self
SUPPORTED_COLORIZATIONS = %w[red green blue].freeze
##
# Produces a random image URL from loremflickr.com.
#
# @param size [String] Specifies the size of image to generate.
# @param search_terms [Array<String>] Adds search terms to the image URL.
# @param match_all [Boolean] Add "all" as part of the URL.
# @return [String]
#
# @example
# Faker::LoremFlickr.image #=> "https://loremflickr.com/300/300"
# Faker::LoremFlickr.image(size: "50x60") #=> "https://loremflickr.com/50/60"
# Faker::LoremFlickr.image(size: "50x60", search_terms: ['sports']) #=> "https://loremflickr.com/50/60/sports"
# Faker::LoremFlickr.image(size: "50x60", search_terms: ['sports', 'fitness']) #=> "https://loremflickr.com/50/60/sports,fitness"
# Faker::LoremFlickr.image(size: "50x60", search_terms: ['sports', 'fitness'], match_all: true) #=> "https://loremflickr.com/50/60/sports,fitness/all"
#
# @faker.version 1.9.0
def image(size: '300x300', search_terms: [], match_all: false)
build_url(size, nil, search_terms, match_all)
end
##
# Produces a random grayscale image URL from loremflickr.com.
#
# @param size [String] Specifies the size of image to generate.
# @param search_terms [Array<String>] Adds search terms to the image URL.
# @param match_all [Boolean] Add "all" as part of the URL.
# @return [String]
#
# @example
# Faker::LoremFlickr.grayscale_image #=> "https://loremflickr.com/g/300/300/all"
# Faker::LoremFlickr.grayscale_image(size: "50x60") #=> "https://loremflickr.com/g/50/60/all"
# Faker::LoremFlickr.grayscale_image(size: "50x60", search_terms: ['sports']) #=> "https://loremflickr.com/g/50/60/sports"
# Faker::LoremFlickr.grayscale_image(size: "50x60", search_terms: ['sports', 'fitness']) #=> "https://loremflickr.com/50/60/g/sports,fitness"
# Faker::LoremFlickr.grayscale_image(size: "50x60", search_terms: ['sports', 'fitness'], match_all: true) #=> "https://loremflickr.com/g/50/60/sports,fitness/all"
#
# @faker.version 1.9.0
def grayscale_image(size: '300x300', search_terms: ['all'], match_all: false)
raise ArgumentError, 'Search terms must be specified for grayscale images' unless search_terms.any?
build_url(size, 'g', search_terms, match_all)
end
##
# Produces a random pixelated image URL from loremflickr.com.
#
# @param size [String] Specifies the size of image to generate.
# @param search_terms [Array<String>] Adds search terms to the image URL.
# @param match_all [Boolean] Add "all" as part of the URL.
# @return [String]
#
# @example
# Faker::LoremFlickr.pixelated_image #=> "https://loremflickr.com/p/300/300/all"
# Faker::LoremFlickr.pixelated_image(size: "50x60") #=> "https://loremflickr.com/p/50/60/all"
# Faker::LoremFlickr.pixelated_image(size: "50x60", search_terms: ['sports']) #=> "https://loremflickr.com/p/50/60/sports"
# Faker::LoremFlickr.pixelated_image(size: "50x60", search_terms: ['sports', 'fitness']) #=> "https://loremflickr.com/p/50/60/sports,fitness"
# Faker::LoremFlickr.pixelated_image(size: "50x60", search_terms: ['sports', 'fitness'], match_all: true) #=> "https://loremflickr.com/p/50/60/sports,fitness/all"
#
# @faker.version 1.9.0
def pixelated_image(size: '300x300', search_terms: ['all'], match_all: false)
raise ArgumentError, 'Search terms must be specified for pixelated images' unless search_terms.any?
build_url(size, 'p', search_terms, match_all)
end
##
# Produces a random colorized image URL from loremflickr.com.
#
# @param size [String] Specifies the size of image to generate.
# @param color [String] Specifies the color of image to generate.
# @param search_terms [Array<String>] Adds search terms to the image URL.
# @param match_all [Boolean] Add "all" as part of the URL.
# @return [String]
#
# @example
# Faker::LoremFlickr.image #=> "https://loremflickr.com/red/300/300/all"
# Faker::LoremFlickr.image(size: "50x60", color: 'blue') #=> "https://loremflickr.com/blue/50/60/all"
# Faker::LoremFlickr.image(size: "50x60", color: 'blue', search_terms: ['sports']) #=> "https://loremflickr.com/blue/50/60/sports"
# Faker::LoremFlickr.image(size: "50x60", color: 'blue', search_terms: ['sports', 'fitness']) #=> "https://loremflickr.com/blue/50/60/sports,fitness"
# Faker::LoremFlickr.image(size: "50x60", color: 'blue', search_terms: ['sports', 'fitness'], match_all: true) #=> "https://loremflickr.com/blue/50/60/sports,fitness/all"
#
# @faker.version 1.9.0
def colorized_image(size: '300x300', color: 'red', search_terms: ['all'], match_all: false)
raise ArgumentError, 'Search terms must be specified for colorized images' unless search_terms.any?
raise ArgumentError, "Supported colorizations are #{SUPPORTED_COLORIZATIONS.join(', ')}" unless SUPPORTED_COLORIZATIONS.include?(color)
build_url(size, color, search_terms, match_all)
end
private
def build_url(size, format, search_terms, match_all)
raise ArgumentError, 'Size should be specified in format 300x300' unless size =~ /^[0-9]+x[0-9]+$/
url_parts = ['https://loremflickr.com']
url_parts << format
url_parts += size.split('x')
url_parts << search_terms.compact.join(',') if search_terms.any?
url_parts << 'all' if match_all
url_parts.compact.join('/')
end
end
end
end
| ruby | MIT | a4d5e503edda970fc085e942018ee235622bfb11 | 2026-01-04T15:37:50.353881Z | false |
faker-ruby/faker | https://github.com/faker-ruby/faker/blob/a4d5e503edda970fc085e942018ee235622bfb11/lib/faker/default/time.rb | lib/faker/default/time.rb | # frozen_string_literal: true
module Faker
class Time < Base
TIME_RANGES = {
all: (0..23),
day: (9..17),
night: (18..23),
morning: (6..11),
afternoon: (12..17),
evening: (17..21),
midnight: (0..4)
}.freeze
class << self
##
# Produce a random time between two times.
#
# @param from [Time, Date, DateTime] The start of the usable time range.
# @param to [Time, Date, DateTime] The end of the usable time range.
# @param format [Symbol] The name of a DateTime format to use.
# @return [Time]
#
# @example
# # Random Stringified time between two times, formatted to the specified I18n format
# # (Examples are from a Rails console with rails-i18n 5.1.1 defaults loaded)
# I18n.locale = 'en-US'
# Faker::Time.between(from: DateTime.now - 1, to: DateTime.now, format: :default) #=> "Tue, 16 Oct 2018 10:48:27 AM -05:00"
# Faker::Time.between(from: DateTime.now - 1, to: DateTime.now, format: :short) #=> "15 Oct 10:48 AM"
# Faker::Time.between(from: DateTime.now - 1, to: DateTime.now, format: :long) #=> "October 15, 2018 10:48 AM"
#
# I18n.locale = 'ja'
# Faker::Time.between(from: DateTime.now - 1, to: DateTime.now, format: :default) #=> "2018/10/15 10:48:27"
# Faker::Time.between(from: DateTime.now - 1, to: DateTime.now, format: :short) #=> "18/10/15 10:48"
# Faker::Time.between(from: DateTime.now - 1, to: DateTime.now, format: :long) #=> "2018年10月16日(火) 10時48分27秒 -0500"
#
# @faker.version 1.5.0
def between(from:, to:, format: nil)
from = get_time_object(from)
to = get_time_object(to)
time = Faker::Base.rand_in_range(from, to)
time_with_format(time, format)
end
##
# Produce a random time between two dates.
#
# @param from [Date] The start of the usable time range.
# @param to [Date] The end of the usable time range.
# @param period [Symbol] The time of day, if any. See {TIME_RANGES}.
# @param format [Symbol] The name of a DateTime format to use.
# @return [Time]
#
# @example
# Faker::Time.between_dates(from: Date.today - 1, to: Date.today, period: :all)
# #=> "2014-09-19 07:03:30 -0700"
# Faker::Time.between_dates(from: Date.today - 1, to: Date.today, period: :day)
# #=> "2014-09-18 16:28:13 -0700"
# Faker::Time.between_dates(from: Date.today - 1, to: Date.today, period: :night)
# #=> "2014-09-20 19:39:38 -0700"
# Faker::Time.between_dates(from: Date.today - 1, to: Date.today, period: :morning)
# #=> "2014-09-19 08:07:52 -0700"
# Faker::Time.between_dates(from: Date.today - 1, to: Date.today, period: :afternoon)
# #=> "2014-09-18 12:10:34 -0700"
# Faker::Time.between_dates(from: Date.today - 1, to: Date.today, period: :evening)
# #=> "2014-09-19 20:21:03 -0700"
# Faker::Time.between_dates(from: Date.today - 1, to: Date.today, period: :midnight)
# #=> "2014-09-20 00:40:14 -0700"
# Faker::Time.between_dates(from: Date.today - 5, to: Date.today + 5, period: :afternoon, format: :default)
# #=> "Fri, 19 Oct 2018 15:17:46 -0500"
#
# @faker.version 1.0.0
def between_dates(from:, to:, period: :all, format: nil)
date = Faker::Date.between(from: from, to: to)
time = date_with_random_time(date, period)
time_with_format(time, format)
end
##
# Produce a random time in the future (up to N days).
#
# @param days [Integer] The maximum number of days to go into the future.
# @param period [Symbol] The time of day, if any. See {TIME_RANGES}.
# @param format [Symbol] The name of a DateTime format to use.
# @return [Time]
#
# @example
# Faker::Time.forward(days: 23, period: :morning)
# # => "2014-09-26 06:54:47 -0700"
# Faker::Time.forward(days: 5, period: :evening, format: :long)
# #=> "October 21, 2018 20:47"
#
# @faker.version 1.5.0
def forward(days: 365, period: :all, format: nil)
time_with_format(date_with_random_time(Faker::Date.forward(days: days), period), format)
end
##
# Produce a random time in the past (up to N days).
#
# @param days [Integer] The maximum number of days to go into the past.
# @param period [Symbol] The time of day, if any. See {TIME_RANGES}.
# @param format [Symbol] The name of a DateTime format to use.
# @return [Time]
#
# @example
# Faker::Time.backward(days: 14, period: :evening)
# #=> "2014-09-17 19:56:33 -0700"
# Faker::Time.backward(days: 5, period: :morning, format: :short)
# #=> "14 Oct 07:44"
#
# @faker.version 1.5.0
def backward(days: 365, period: :all, format: nil)
time_with_format(date_with_random_time(Faker::Date.backward(days: days), period), format)
end
private
def date_with_random_time(date, period)
::Time.local(date.year, date.month, date.day, hours(period), minutes, seconds)
end
def time_with_format(time, format)
format.nil? ? time : I18n.localize(time, format: format)
end
def hours(period)
raise ArgumentError, 'invalid period' unless TIME_RANGES.key? period
sample(TIME_RANGES[period].to_a)
end
def minutes
seconds
end
def seconds
sample((0..59).to_a)
end
def get_time_object(time)
time = ::Time.parse(time) if time.is_a? String
time = time.to_time if time.respond_to?(:to_time)
time
end
end
end
end
| ruby | MIT | a4d5e503edda970fc085e942018ee235622bfb11 | 2026-01-04T15:37:50.353881Z | false |
faker-ruby/faker | https://github.com/faker-ruby/faker/blob/a4d5e503edda970fc085e942018ee235622bfb11/lib/faker/default/file.rb | lib/faker/default/file.rb | # frozen_string_literal: true
module Faker
class File < Base
class << self
##
# Produces a random directory name.
#
# @param segment_count [Integer] Specifies the number of nested folders in the generated string.
# @param root [String] Specifies the root of the generated string.
# @param directory_separator [String] Specifies the separator between the segments.
# @return [String]
#
# @example
# Faker::File.dir #=> "et_error/sint_voluptas/quas_veritatis"
# Faker::File.dir(segment_count: 2) #=> "ea-suscipit/ut-deleniti"
# Faker::File.dir(segment_count: 3, root: nil, directory_separator: '/') #=> "est_porro/fugit_eveniet/incidunt-autem"
# Faker::File.dir(segment_count: 3, root: nil, directory_separator: '\\') #=> "aut-ullam\\quia_quisquam\\ut-eos"
#
# @faker.version 1.6.4
def dir(segment_count: 3, root: nil, directory_separator: ::File::Separator)
Array
.new(segment_count) { Faker::Internet.slug }
.unshift(root)
.compact
.join(directory_separator)
.squeeze(directory_separator)
end
##
# Produces a random file extension.
#
# @return [String]
#
# @example
# Faker::File.extension #=> "mp3"
#
# @faker.version 1.6.4
def extension
fetch('file.extension')
end
##
# Produces a random mime type.
#
# @return [String]
#
# @example
# Faker::File.mime_type #=> "application/pdf"
#
# @faker.version next
def mime_type(media_type: nil)
media_type ? fetch("file.mime_type.#{media_type}") : sample(sample(translate('faker.file.mime_type').values))
end
##
# Produces a random file name.
#
# @param dir [String] Specifies the path used for the generated file.
# @param name [String] Specifies the filename used for the generated file.
# @param ext [String] Specifies the extension used the generated file.
# @param directory_separator [String] Specifies the separator between the directory and name elements.
# @return [String]
#
# @example
# Faker::File.file_name(dir: 'path/to') #=> "path/to/something_random.jpg"
# Faker::File.file_name(dir: 'foo/bar', name: 'baz') #=> "foo/bar/baz.zip"
# Faker::File.file_name(dir: 'foo/bar', name: 'baz', ext: 'doc') #=> "foo/bar/baz.doc"
# Faker::File.file_name(dir: 'foo/bar', name: 'baz', ext: 'mp3', directory_separator: '\\') #=> "foo/bar\\baz.mp3"
#
# @faker.version 1.6.4
def file_name(dir: nil, name: nil, ext: nil, directory_separator: ::File::Separator)
dir ||= dir(segment_count: 1)
name ||= Faker::Lorem.word.downcase
ext ||= extension
[dir, name].join(directory_separator) + ".#{ext}"
end
end
end
end
| ruby | MIT | a4d5e503edda970fc085e942018ee235622bfb11 | 2026-01-04T15:37:50.353881Z | false |
faker-ruby/faker | https://github.com/faker-ruby/faker/blob/a4d5e503edda970fc085e942018ee235622bfb11/lib/faker/default/slack_emoji.rb | lib/faker/default/slack_emoji.rb | # frozen_string_literal: true
module Faker
class SlackEmoji < Base
class << self
##
# Produces a random slack emoji from people category.
#
# @return [String]
#
# @example
# Faker::SlackEmoji.people #=> ":sleepy:"
#
# @faker.version 1.5.0
def people
fetch('slack_emoji.people')
end
##
# Produces a random slack emoji from nature category.
#
# @return [String]
#
# @example
# Faker::SlackEmoji.nature #=> ":mount_fuji:"
#
# @faker.version 1.5.0
def nature
fetch('slack_emoji.nature')
end
##
# Produces a random slack emoji from food and drink category.
#
# @return [String]
#
# @example
# Faker::SlackEmoji.food_and_drink #=> ":beers:"
#
# @faker.version 1.5.0
def food_and_drink
fetch('slack_emoji.food_and_drink')
end
##
# Produces a random slack emoji from celebration category.
#
# @return [String]
#
# @example
# Faker::SlackEmoji.celebration #=> ":tada:"
#
# @faker.version 1.5.0
def celebration
fetch('slack_emoji.celebration')
end
##
# Produces a random slack emoji from activity category.
#
# @return [String]
#
# @example
# Faker::SlackEmoji.activity #=> ":soccer:"
#
# @faker.version 1.5.0
def activity
fetch('slack_emoji.activity')
end
##
# Produces a random slack emoji from travel and places category.
#
# @return [String]
#
# @example
# Faker::SlackEmoji.travel_and_places #=> ":metro:"
#
# @faker.version 1.5.0
def travel_and_places
fetch('slack_emoji.travel_and_places')
end
##
# Produces a random slack emoji from objects and symbols category.
#
# @return [String]
#
# @example
# Faker::SlackEmoji.objects_and_symbols #=> ":id:"
#
# @faker.version 1.5.0
def objects_and_symbols
fetch('slack_emoji.objects_and_symbols')
end
##
# Produces a random slack emoji from custom category.
#
# @return [String]
#
# @example
# Faker::SlackEmoji.custom #=> ":slack:"
#
# @faker.version 1.5.0
def custom
fetch('slack_emoji.custom')
end
##
# Produces a random slack emoji from any category.
#
# @return [String]
#
# @example
# Faker::SlackEmoji.emoji #=> ":pizza:"
#
# @faker.version 1.5.0
def emoji
parse('slack_emoji.emoji')
end
end
end
end
| ruby | MIT | a4d5e503edda970fc085e942018ee235622bfb11 | 2026-01-04T15:37:50.353881Z | false |
faker-ruby/faker | https://github.com/faker-ruby/faker/blob/a4d5e503edda970fc085e942018ee235622bfb11/lib/faker/default/code.rb | lib/faker/default/code.rb | # frozen_string_literal: true
module Faker
class Code < Base
flexible :code
class << self
##
# Produces a random NPI (National Provider Identifier) code.
#
# @return [String]
#
# @example
# Faker::Code.npi #=> "9804062802"
#
# @faker.version 1.9.4
def npi
rand(10**10).to_s.rjust(10, '0')
end
##
# Produces a random ISBN (International Standard Book Number) code.
#
# @param base [Integer] the length of the code to generate (either 10 or 13)
# @return [String]
#
# @example
# Faker::Code.isbn(base: 13) #=> "896579606969-8"
# @example
# Faker::Code.isbn #=> "170366802-2"
#
# @faker.version 2.2.0
def isbn(base: 10)
case base
when 10 then generate_base10_isbn
when 13 then generate_base13_isbn
else raise ArgumentError, 'base must be 10 or 13'
end
end
##
# Produces a random EAN (European Article Number) code.
#
# @param base [Integer] the length of the code to generate (either 8 or 13)
# @return [String]
#
# @example
# Faker::Code.ean(base: 8) #=> "36941070"
# @example
# Faker::Code.ean #=> "9941880131907"
#
# @faker.version 2.2.0
def ean(base: 13)
case base
when 8 then generate_base8_ean
when 13 then generate_base13_ean
else raise ArgumentError, 'base must be 8 or 13'
end
end
##
# Produces a random RUT (Rol Unico Nacional) code.
#
# @return [String]
#
# @example
# Faker::Code.rut #=> "91611842-2"
#
# @faker.version 1.9.4
def rut
value = Number.number(digits: 8).to_s
vd = rut_verificator_digit(value)
value << "-#{vd}"
end
##
# Produces a random NRIC (National Registry Identity Card) code.
# By default generates a Singaporean NRIC ID for someone
# who is born between the age of 18 and 65.
#
# @param min_age [Integer] the min age of the person in years
# @param max_age [Integer] the max age of the person in years
# @return [String]
#
# @example
# Faker::Code.nric(min_age: 25, max_age: 50) #=> "S9347283G"
# @example
# Faker::Code.nric(max_age: 55) #=> "S7876903C"
# @example
# Faker::Code.nric(min_age: 25) #=> "S6281697Z"
# @example
# Faker::Code.nric #=> "S6372958B"
#
# @faker.version 2.2.0
def nric(min_age: 18, max_age: 65)
birthyear = Date.birthday(min_age: min_age, max_age: max_age).year
generate(:string) do |g|
g.computed(name: :prefix) do
if birthyear < 2000
'S'
else
'T'
end
end
g.computed(name: :yy) do
birthyear.to_s[-2..]
end
g.int(name: :values, length: 5)
g.computed(name: :check, deps: %i[prefix yy values]) do |prefix, yy, values|
generate_nric_check_alphabet("#{yy}#{values}", prefix)
end
end
end
##
# Produces a random IMEI (International Mobile Equipment Number) code.
#
# @return [String]
#
# @example
# Faker::Code.imei #=> "492033129092256"
#
# @faker.version 1.9.4
def imei
generate_imei
end
##
# Retrieves a real Amazon ASIN code from https://archive.org/details/asin_listing
#
# @return [String]
#
# @example
# Faker::Code.asin #=> "B000MZW1GE"
#
# @faker.version 1.9.4
def asin
fetch('code.asin')
end
##
# Produces a random SIN (Social Insurance Number for Canada) code.
#
# @return [String]
#
# @example
# Faker::Code.sin #=> "996586962"
#
# @faker.version 1.9.4
def sin
# 1 - province or temporary resident
# 2-8 - random numbers
# 9 - checksum
# 1st digit. 8,0 are not used
registry = Faker::Base.sample([1, 2, 3, 4, 5, 6, 7, 9]).to_s
# generate 2nd to 8th
partial = Array.new(7) { Faker::Config.random.rand(0..9) }.join
# Generate 9th digit
check_digit = generate_sin_check_digit("#{registry}#{partial}0").to_s
registry + partial + check_digit
end
private
# Reporting body identifier
RBI = %w[01 10 30 33 35 44 45 49 50 51 52 53 54 86 91 98 99].freeze
private_constant :RBI
def generate_imei
str = Array.new(15, 0)
sum = 0
len = 15
# Fill in the first two values of the string based with the specified prefix.
# Reporting Body Identifier list: http://en.wikipedia.org/wiki/Reporting_Body_Identifier
arr = sample(RBI)
str[0] = arr[0].to_i
str[1] = arr[1].to_i
pos = 2
# Fill all the remaining numbers except for the last one with random values.
while pos < (len - 1)
str[pos] = rand(0..9)
pos += 1
end
# Calculate the Luhn checksum of the values thus far
len_offset = (len + 1) % 2
(0..(len - 1)).each do |position|
if (position + len_offset).odd?
t = str[position] * 2
t -= 9 if t > 9
sum += t
else
sum += str[position]
end
end
# Choose the last digit so that it causes the entire string to pass the checksum.
str[len - 1] = (10 - (sum % 10)) % 10
# Output the IMEI value.
str.join
end
def generate_base10_isbn
generate(:string) do |g|
g.int(name: :values, length: 9)
g.lit('-')
g.computed(name: :checksum, deps: [:values]) do |values|
remainder = sum(values.to_s) { |value, offset| (offset + 1) * value.to_i } % 11
if remainder == 10
'X'
else
remainder.to_s
end
end
end
end
def generate_base13_isbn
generate(:string) do |g|
g.int(name: :values, length: 12)
g.lit('-')
g.computed(name: :checksum, deps: [:values]) do |values|
remainder = sum(values.to_s) { |value, offset| offset.even? ? value.to_i : value.to_i * 3 } % 10
(10 - remainder) % 10
end
end
end
def sum(values)
values.chars.each_with_index.inject(0) do |sum, (value, index)|
sum + yield(value, index)
end
end
def generate_base8_ean
generate(:string) do |g|
g.int(name: :values, length: 7)
g.computed(name: :checksum, deps: [:values]) do |values|
check_digit = 10 - values.to_s.chars.each_with_index.inject(0) { |s, (v, i)| s + v.to_i * EAN_CHECK_DIGIT8[i] } % 10
if check_digit == 10
0
else
check_digit
end
end
end
end
def generate_base13_ean
generate(:string) do |g|
g.int(name: :values, length: 12)
g.computed(name: :checksum, deps: [:values]) do |values|
check_digit = 10 - values.to_s.chars.each_with_index.inject(0) { |s, (v, i)| s + v.to_i * EAN_CHECK_DIGIT13[i] } % 10
if check_digit == 10
0
else
check_digit
end
end
end
end
EAN_CHECK_DIGIT8 = [3, 1, 3, 1, 3, 1, 3].freeze
private_constant :EAN_CHECK_DIGIT8
EAN_CHECK_DIGIT13 = [1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3].freeze
private_constant :EAN_CHECK_DIGIT13
def rut_verificator_digit(rut)
total = rut.to_s.rjust(8, '0').chars.zip(%w[3 2 7 6 5 4 3 2]).collect { |a, b| a.to_i * b.to_i }.inject(:+)
(11 - total % 11).to_s.gsub('10', 'k').gsub('11', '0')
end
def generate_nric_check_alphabet(values, prefix)
weight = %w[2 7 6 5 4 3 2]
total = values.chars.zip(weight).collect { |a, b| a.to_i * b.to_i }.inject(:+)
total += 4 if prefix == 'T'
%w[A B C D E F G H I Z J][10 - total % 11]
end
def generate_sin_check_digit(digits)
# Fast Luhn checksum code from luhn.js:
# https://gist.github.com/ShirtlessKirk/2134376
len = 9
mul = 0
luhn_arr = [
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[0, 2, 4, 6, 8, 1, 3, 5, 7, 9]
]
sum = 0
while len.positive?
len -= 1
num = digits[len].to_i
sum += luhn_arr[mul][num]
mul ^= 1
end
checksum = sum % 10
checksum.zero? ? checksum : (10 - checksum)
end
end
end
end
| ruby | MIT | a4d5e503edda970fc085e942018ee235622bfb11 | 2026-01-04T15:37:50.353881Z | false |
faker-ruby/faker | https://github.com/faker-ruby/faker/blob/a4d5e503edda970fc085e942018ee235622bfb11/lib/faker/default/boolean.rb | lib/faker/default/boolean.rb | # frozen_string_literal: true
module Faker
class Boolean < Base
class << self
##
# Produces a boolean
#
# @param true_ratio [Float] The likelihood (as a float, out of 1.0) for the method to return `true`.
# @return [Boolean]
#
# @example
# Faker::Boolean.boolean #=> true
# @example
# Faker::Boolean.boolean(true_ratio: 0.2) #=> false
#
# @faker.version 1.6.2
#
def boolean(true_ratio: 0.5) # rubocop:disable Naming/PredicateMethod
(rand < true_ratio)
end
end
end
end
| ruby | MIT | a4d5e503edda970fc085e942018ee235622bfb11 | 2026-01-04T15:37:50.353881Z | false |
faker-ruby/faker | https://github.com/faker-ruby/faker/blob/a4d5e503edda970fc085e942018ee235622bfb11/lib/faker/default/currency.rb | lib/faker/default/currency.rb | # frozen_string_literal: true
module Faker
class Currency < Base
class << self
##
# Produces the name of a currency.
#
# @return [String]
#
# @example
# Faker::Currency.name #=> "Swedish Krona"
#
# @faker.version 1.9.0
def name
fetch('currency.name')
end
##
# Produces a currency code.
#
# @return [String]
#
# @example
# Faker::Currency.code #=> "USD"
#
# @faker.version 1.9.0
def code
fetch('currency.code')
end
##
# Produces a currency symbol.
#
# @return [String]
#
# @example
# Faker::Currency.symbol #=> "$"
#
# @faker.version 1.9.0
def symbol
fetch('currency.symbol')
end
end
end
end
| ruby | MIT | a4d5e503edda970fc085e942018ee235622bfb11 | 2026-01-04T15:37:50.353881Z | false |
faker-ruby/faker | https://github.com/faker-ruby/faker/blob/a4d5e503edda970fc085e942018ee235622bfb11/lib/faker/default/twitter.rb | lib/faker/default/twitter.rb | # frozen_string_literal: true
module Faker
class Twitter < Base
class << self
##
# Produces a random Twitter user.
#
# @param include_status [Boolean] Include or exclude user status details
# @param include_email [Boolean] Include or exclude user email details
# @return [Hash]
#
# @example
# Faker::Twitter.user #=> {:id=>8821452687517076614, :name=>"Lincoln Paucek", :screen_name=>"cody"...
# Faker::Twitter.user(include_status: false) # Just get a user object with no embed status
# Faker::Twitter.user(include_email: true) # Simulate an authenticated user with the email permission
#
# @faker.version 1.7.3
def user(include_status: true, include_email: false)
warn('DEPRECATION WARNING: Faker::Twitter is deprecated. Use Faker::X instead. Some return attributes \
will be removed, check the docs for more details.')
user_id = id
background_image_url = Faker::LoremFlickr.image(size: '600x400')
profile_image_url = Faker::Avatar.image(slug: user_id, size: '48x48')
user = {
id: user_id,
id_str: user_id.to_s,
contributors_enabled: Faker::Boolean.boolean(true_ratio: 0.1),
created_at: created_at,
default_profile_image: Faker::Boolean.boolean(true_ratio: 0.1),
default_profile: Faker::Boolean.boolean(true_ratio: 0.1),
description: Faker::Lorem.sentence,
entities: user_entities,
favourites_count: Faker::Number.between(to: 1, from: 100_000),
follow_request_sent: false,
followers_count: Faker::Number.between(to: 1, from: 10_000_000),
following: false,
friends_count: Faker::Number.between(to: 1, from: 100_000),
geo_enabled: Faker::Boolean.boolean(true_ratio: 0.1),
is_translation_enabled: Faker::Boolean.boolean(true_ratio: 0.1),
is_translator: Faker::Boolean.boolean(true_ratio: 0.1),
lang: Faker::Address.country_code,
listed_count: Faker::Number.between(to: 1, from: 1000),
location: "#{Faker::Address.city}, #{Faker::Address.state_abbr}, #{Faker::Address.country_code}",
name: Faker::Name.name,
notifications: false,
profile_background_color: Faker::Color.hex_color,
profile_background_image_url_https: background_image_url,
profile_background_image_url: background_image_url.sub('https://', 'http://'),
profile_background_tile: Faker::Boolean.boolean(true_ratio: 0.1),
profile_banner_url: Faker::LoremFlickr.image(size: '1500x500'),
profile_image_url_https: profile_image_url,
profile_image_url: profile_image_url.sub('https://', 'http://'),
profile_link_color: Faker::Color.hex_color,
profile_sidebar_border_color: Faker::Color.hex_color,
profile_sidebar_fill_color: Faker::Color.hex_color,
profile_text_color: Faker::Color.hex_color,
profile_use_background_image: Faker::Boolean.boolean(true_ratio: 0.4),
protected: Faker::Boolean.boolean(true_ratio: 0.1),
screen_name: screen_name,
statuses_count: Faker::Number.between(to: 1, from: 100_000),
time_zone: Faker::Address.time_zone,
url: Faker::Internet.url(host: 'example.com'),
utc_offset: utc_offset,
verified: Faker::Boolean.boolean(true_ratio: 0.1)
}
user[:status] = Faker::Twitter.status(include_user: false) if include_status
user[:email] = Faker::Internet.email if include_email
user
end
##
# Produces a random Twitter user.
#
# @param include_user [Boolean] Include or exclude user details
# @param include_photo [Boolean] Include or exclude user photo
# @return [Hash]
#
# @example
# Faker::Twitter.status #=> {:id=>8821452687517076614, :text=>"Ea et laboriosam vel non."...
# Faker::Twitter.status(include_user: false) # Just get a status object with no embed user
# Faker::Twitter.status(include_photo: true) # Includes entities for an attached image
#
# @faker.version 1.7.3
def status(include_user: true, include_photo: false)
warn('DEPRECATION WARNING: Faker::Twitter is deprecated. Use Faker::X instead. Some return attributes \
will be removed, check the docs for more details.')
status_id = id
status = {
id: status_id,
id_str: status_id.to_s,
contributors: nil,
coordinates: nil,
created_at: created_at,
entities: status_entities(include_photo: include_photo),
favorite_count: Faker::Number.between(to: 1, from: 10_000),
favorited: false,
geo: nil,
in_reply_to_screen_name: nil,
in_reply_to_status_id: nil,
in_reply_to_user_id_str: nil,
in_reply_to_user_id: nil,
is_quote_status: false,
lang: Faker::Address.country_code,
nil: nil,
place: nil,
possibly_sensitive: Faker::Boolean.boolean(true_ratio: 0.1),
retweet_count: Faker::Number.between(to: 1, from: 10_000),
retweeted_status: nil,
retweeted: false,
source: "<a href=\"#{Faker::Internet.url(host: 'example.com')}\" rel=\"nofollow\">#{Faker::Company.name}</a>",
text: Faker::Lorem.sentence,
truncated: false
}
status[:user] = Faker::Twitter.user(include_status: false) if include_user
status[:text] = "#{status[:text]} #{status[:entities][:media].first[:url]}" if include_photo
status
end
##
# Produces a random screen name.
#
# @return [String]
#
# @example
# Faker::Twitter.screen_name #=> "audreanne_hackett"
#
# @faker.version 1.7.3
def screen_name
warn('DEPRECATION WARNING: Faker::Twitter is deprecated. Use Faker::X instead.')
Faker::Internet.username(specifier: nil, separators: ['_'])[0...20]
end
private
def id
Faker::Number.between(from: 1, to: 9_223_372_036_854_775_807)
end
def created_at
Faker::Date.between(from: '2006-03-21', to: ::Date.today).strftime('%a %b %d %H:%M:%S %z %Y')
end
def utc_offset
Faker::Number.between(to: -43_200, from: 50_400)
end
def user_entities
{
url: {
urls: []
},
description: {
urls: []
}
}
end
def status_entities(include_photo: false)
entities = {
hashtags: [],
symbols: [],
user_mentions: [],
urls: []
}
entities[:media] = [photo_entity] if include_photo
entities
end
def photo_entity
media_url = Faker::LoremFlickr.image(size: '1064x600')
media_id = id
{
id: media_id,
id_str: media_id.to_s,
indices: [
103,
126
],
media_url: media_url.sub('https://', 'http://'),
media_url_https: media_url,
url: Faker::Internet.url(host: 'example.com'),
display_url: 'example.com',
expanded_url: Faker::Internet.url(host: 'example.com'),
type: 'photo',
sizes: {
medium: {
w: 1064,
h: 600,
resize: 'fit'
},
large: {
w: 1064,
h: 600,
resize: 'fit'
},
small: {
w: 680,
h: 383,
resize: 'fit'
},
thumb: {
w: 150,
h: 150,
resize: 'crop'
}
}
}
end
end
end
class X < Base
class << self
##
# Produces a random X user based on X's v2 API.
#
# @return [Hash]
#
# @example
# Faker::X.user #=> { data: [{:id=>"8821452687517076614", :name=>"Lincoln Paucek", :screen_name=>"cody"...
#
# @faker.version 1.7.3
def user
author_id = Faker::Number.between(from: 1, to: 9_223_372_036_854_775_807)
{
data: [
{
author_id: author_id.to_s,
id: id.to_s,
text: Faker::Lorem.sentence
}
],
includes: {
users: [
{
public_metrics: {
followers_count: Faker::Number.between(to: 1, from: 1_000),
following_count: Faker::Number.between(to: 1, from: 200),
tweet_count: Faker::Number.between(to: 1, from: 10_000),
listed_count: Faker::Number.between(to: 1, from: 1_000)
},
username: screen_name,
pinned_tweet_id: Faker::Number.between(from: 1, to: 9_223_372_036_854_775_807).to_s,
entities: user_entities,
description: Faker::Lorem.sentence,
name: Faker::Name.name,
verified: Faker::Boolean.boolean(true_ratio: 0.1),
location: Faker::Internet.public_ip_v4_address,
id: author_id.to_s,
protected: Faker::Boolean.boolean(true_ratio: 0.1),
url: url,
profile_image_url: Faker::Avatar.image(slug: id, size: '48x48'),
created_at: created_at
}
]
}
}
end
##
# Produces a random X tweet with default attributes.
#
# @param include_user [Boolean] Include user details
# @param include_media [Boolean] Include user media (photo) details
# @return [Hash]
#
# @example
# Faker::X.tweet #=> { data: [{:id=>"8821452687517076614", :text=>"Ea et laboriosam vel non."...
# Faker::X.tweet(include_media: true) # Get a tweet object with a photo media attachment
# Faker::X.tweet(include_user: true) # Get a tweet object with an user details
#
# @faker.version 1.7.3
def tweet(include_media: false, include_user: false)
tweet = {}
tweet_object = tweet_item
includes = {}
if include_media
media_key = Faker::Number.between(from: 1, to: 9_223_372_036_854_775_807).to_s
includes[:media] = media(media_key)
tweet_object[:attachments] = { media_keys: [media_key] }
end
includes[:users] = user[:includes][:users] if include_user
tweet[:data] = [
tweet_object
]
unless includes.empty?
tweet[:includes] = includes
end
tweet
end
##
# Produces a random screen_name.
#
# @return [String]
#
# @example
# Faker::X.screen_name #=> "audreanne_hackett"
#
# @faker.version 1.7.3
def screen_name
Faker::Internet.username(specifier: nil, separators: ['_'])[0...20]
end
private
def id
Faker::Number.between(from: 1, to: 9_223_372_036_854_775_807)
end
def created_at
Faker::Date.between(from: '2006-03-21', to: ::Date.today).to_time.utc.iso8601(3)
end
def url
"https://t.co/#{Faker::Lorem.characters(number: 10)}"
end
def user_entities
entities = tweet_entities
{
url: {
urls: entities[:urls]
},
description: {
hashtags: entities[:hashtags]
}
}
end
def tweet_entities
display_url = Faker::Internet.url(host: 'example.com')
{
urls: [
{
start: 0,
end: 5,
url: url,
expanded_url: display_url,
display_url: display_url.sub('http://', '')
}
],
hashtags: [
{
start: 0,
end: 5,
tag: Faker::Lorem.word.capitalize
}
]
}
end
def media(media_key)
expanded_url = Faker::LoremFlickr.image(size: '1064x600')
[{
height: Faker::Number.between(to: 1, from: 1000),
media_key: media_key,
type: 'photo',
preview_image_url: expanded_url,
width: Faker::Number.between(to: 1, from: 2000),
alt_text: Faker::Lorem.sentence
}]
end
def tweet_item
conversation_id = id.to_s
{
id: conversation_id,
text: Faker::Lorem.sentence,
lang: sample(%w[en fr es pt it ja]),
conversation_id: conversation_id,
created_at: created_at,
author_id: Faker::Number.between(from: 1, to: 9_223_372_036_854_775_807).to_s,
public_metrics: {
retweet_count: Faker::Number.between(to: 1, from: 100),
reply_count: Faker::Number.between(to: 1, from: 20),
like_count: Faker::Number.between(to: 1, from: 25),
quote_count: Faker::Number.between(to: 1, from: 10)
},
possibly_sensitive: Faker::Boolean.boolean(true_ratio: 0.1),
entities: tweet_entities
}
end
end
end
end
| ruby | MIT | a4d5e503edda970fc085e942018ee235622bfb11 | 2026-01-04T15:37:50.353881Z | false |
faker-ruby/faker | https://github.com/faker-ruby/faker/blob/a4d5e503edda970fc085e942018ee235622bfb11/lib/faker/default/commerce.rb | lib/faker/default/commerce.rb | # frozen_string_literal: true
module Faker
class Commerce < Base
class << self
##
# Produces a random color.
#
# @return [String]
#
# @example
# Faker::Commerce.color #=> "lavender"
#
# @faker.version 1.2.0
def color
fetch('color.name')
end
##
# Produces a random promotion code.
#
# @param digits [Integer] Updates the number of numerical digits used to generate the promotion code.
# @return [String]
#
# @example
# Faker::Commerce.promotion_code #=> "AmazingDeal829102"
# Faker::Commerce.promotion_code(digits: 2) #=> "AmazingPrice57"
#
# @faker.version 1.7.0
def promotion_code(digits: 6)
[
fetch('commerce.promotion_code.adjective'),
fetch('commerce.promotion_code.noun'),
Faker::Number.number(digits: digits)
].join
end
##
# Produces a random department.
#
# @param max [Integer] Updates the maximum number of names used to generate the department name.
# @param fixed_amount [Boolean] Fixes the amount of departments to use instead of using a range.
# @return [String]
#
# @example
# Faker::Commerce.department #=> "Grocery, Health & Beauty"
# Faker::Commerce.department(max: 5) #=> "Grocery, Books, Health & Beauty"
# Faker::Commerce.department(max: 2, fixed_amount: true) #=> "Books & Tools"
#
# @faker.version 1.2.0
def department(max: 3, fixed_amount: false)
num = max if fixed_amount
num ||= 1 + rand(max)
categories = categories(num)
if categories.is_a?(Array)
if categories.length > 1
merge_categories(categories)
else
categories[0]
end
else
categories
end
end
##
# Produces a random product name.
#
# @return [String]
#
# @example
# Faker::Commerce.product_name #=> "Practical Granite Shirt"
#
# @faker.version 1.2.0
def product_name
"#{fetch('commerce.product_name.adjective')} #{fetch('commerce.product_name.material')} #{fetch('commerce.product_name.product')}"
end
##
# Produces a random material.
#
# @return [String]
#
# @example
# Faker::Commerce.material #=> "Plastic"
#
# @faker.version 1.5.0
def material
fetch('commerce.product_name.material')
end
##
# Produces a random product price.
#
# @param range [Range] A range to generate the random number within.
# @param as_string [Boolean] Changes the return value to [String].
# @return [Float]
#
# @example
# Faker::Commerce.price #=> 44.6
# Faker::Commerce.price(range: 0..10.0, as_string: true) #=> "2.18"
#
# @faker.version 1.2.0
def price(range: 0..100.0, as_string: false)
price = (rand(range) * 100).floor / 100.0
if as_string
price_parts = price.to_s.split('.')
price = "#{price_parts[0]}.#{price_parts[-1].ljust(2, '0')}"
end
price
end
##
# Produces a randomized string of a brand name
# @example
# Faker::Commerce.brand #=> 'Apple'
#
# @return [string]
#
# @faker.version next
#
##
def brand
fetch('commerce.brand')
end
##
# Produces a randomized string of a vendor name
# @example
# Faker::Commerce.vendor #=> 'Dollar General'
#
# @return [string]
#
# @faker.version next
#
##
def vendor
fetch('commerce.vendor')
end
private
def categories(num)
sample(fetch_all('commerce.department'), num)
end
def merge_categories(categories)
separator = fetch('separator')
comma_separated = categories.slice!(0...-1).join(', ')
[comma_separated, categories[0]].join(separator)
end
end
end
end
| ruby | MIT | a4d5e503edda970fc085e942018ee235622bfb11 | 2026-01-04T15:37:50.353881Z | false |
faker-ruby/faker | https://github.com/faker-ruby/faker/blob/a4d5e503edda970fc085e942018ee235622bfb11/lib/faker/default/blood.rb | lib/faker/default/blood.rb | # frozen_string_literal: true
module Faker
class Blood < Base
flexible :blood
class << self
##
# Produces a random blood type.
#
# @return [String]
#
# @example
# Faker::Blood.type #=> "AB"
#
# @faker.version 2.13.0
def type
fetch('blood.type')
end
##
# Produces a random blood RH-Factor.
#
# @return [String]
#
# @example
# Faker::Blood.rh_factor #=> "-"
#
# @faker.version 2.13.0
def rh_factor
fetch('blood.rh_factor')
end
##
# Produces a random blood group name.
#
# @return [String]
#
# @example
# Faker::Blood.group #=> "AB-"
#
# @faker.version 2.13.0
def group
parse('blood.group')
end
end
end
end
| ruby | MIT | a4d5e503edda970fc085e942018ee235622bfb11 | 2026-01-04T15:37:50.353881Z | false |
faker-ruby/faker | https://github.com/faker-ruby/faker/blob/a4d5e503edda970fc085e942018ee235622bfb11/lib/faker/default/address.rb | lib/faker/default/address.rb | # frozen_string_literal: true
module Faker
class Address < Base
flexible :address
class << self
##
# Produces the name of a city.
#
# @param options [Hash]
# @option with_state [Boolean] Whether to include the state name in the output.
# @return [String]
#
# @example
# Faker::Address.city #=> "Imogeneborough"
# Faker::Address.city(options: { with_state: true })
# #=> "Northfort, California"
#
# @faker.version 0.3.0
def city(options: {})
parse(options[:with_state] ? 'address.city_with_state' : 'address.city')
end
##
# Produces a street name.
#
# @return [String]
#
# @example
# Faker::Address.street_name #=> "Larkin Fork"
#
# @faker.version 0.3.0
def street_name
parse('address.street_name')
end
##
# Produces a street address.
#
# @param include_secondary [Boolean] Whether or not to include the secondary address.
# @return [String]
#
# @example
# Faker::Address.street_address #=> "282 Kevin Brook"
#
# @faker.version 0.3.0
def street_address(include_secondary: false)
numerify(parse('address.street_address') + (include_secondary ? " #{secondary_address}" : ''))
end
##
# Produces a secondary address.
#
# @return [String]
#
# @example
# Faker::Address.secondary_address #=> "Apt. 672"
#
# @faker.version 0.3.0
def secondary_address
bothify(fetch('address.secondary_address'))
end
##
# Produces a building number.
#
# @return [String]
#
# @example
# Faker::Address.building_number #=> "7304"
#
# @faker.version 0.3.0
def building_number
bothify(fetch('address.building_number'))
end
##
# Produces the name of a community.
#
# @return [String]
#
# @example
# Faker::Address.community #=> "University Crossing"
#
# @faker.version 1.8.0
def community
parse('address.community')
end
##
#
# Produces a mail box number.
# @return [String]
#
# @example
# Faker::Address.mail_box #=> "PO Box 123"
#
# @faker.version 2.9.1
def mail_box
bothify(fetch('address.mail_box'))
end
##
# Produces a Zip Code.
#
# @param state_abbreviation [String] an abbreviation for a state where the zip code should be located.
# @return [String]
#
# @example
# Faker::Address.zip_code #=> "58517"
# Faker::Address.zip_code #=> "23285-4905"
# Faker::Address.zip_code(state_abbreviation: 'CO') #=> "80011"
#
# @faker.version 0.3.0
def zip_code(state_abbreviation: '')
if state_abbreviation.empty?
letterified_string = letterify(fetch('address.postcode'))
return numerify(letterified_string, leading_zero: true)
end
# provide a zip code that may be valid for the state provided
# note: zip code may appear in the correct format for the state provided but may not be an actual state zip.
bothify(fetch("address.postcode_by_state.#{state_abbreviation}"))
end
##
# Produces the name of a time zone.
#
# @return [String]
#
# @example
# Faker::Address.time_zone #=> "Asia/Yakutsk"
#
# @faker.version 1.2.0
def time_zone
fetch('address.time_zone')
end
alias zip zip_code
alias postcode zip_code
##
# Produces a street suffix.
#
# @return [String]
#
# @example
# Faker::Address.street_suffix #=> "Street"
#
# @faker.version 0.3.0
def street_suffix
fetch('address.street_suffix')
end
##
# Produces a city suffix.
#
# @return [String]
#
# @example
# Faker::Address.city_suffix #=> "fort"
#
# @faker.version 0.3.0
def city_suffix
fetch('address.city_suffix')
end
##
# Produces a city prefix.
#
# @return [String]
#
# @example
# Faker::Address.city_prefix #=> "Lake"
#
# @faker.version 0.3.0
def city_prefix
fetch('address.city_prefix')
end
##
# Produces a state abbreviation.
#
# @return [String]
#
# @example
# Faker::Address.state_abbr #=> "AP"
#
# @faker.version 0.3.0
def state_abbr
fetch('address.state_abbr')
end
##
# Produces the name of a state.
#
# @return [String]
#
# @example
# Faker::Address.state #=> "California"
#
# @faker.version 0.3.0
def state
fetch('address.state')
end
##
# Produces the name of a country.
#
# @return [String]
#
# @example
# Faker::Address.country #=> "French Guiana"
#
# @faker.version 0.3.0
def country
fetch('address.country')
end
##
# Produces a country by ISO country code. See the
# [List of ISO 3166 country codes](https://en.wikipedia.org/wiki/List_of_ISO_3166_country_codes)
# on Wikipedia for a full list.
#
# @param code [String] An ISO country code.
# @return [String]
#
# @example
# Faker::Address.country_by_code(code: 'NL') #=> "Netherlands"
#
# @faker.version 1.9.2
def country_by_code(code: 'US')
fetch("address.country_by_code.#{code}")
end
##
# Produces an ISO 3166 country code when given a country name.
#
# @param name [String] Country name in snake_case format.
# @return [String]
#
# @example
# Faker::Address.country_name_to_code(name: 'united_states') #=> "US"
#
# @faker.version 1.9.2
def country_name_to_code(name: 'united_states')
fetch("address.country_by_name.#{name}")
end
##
# Produces an ISO 3166 country code.
#
# @return [String]
#
# @example
# Faker::Address.country_code #=> "IT"
#
# @faker.version 1.4.0
def country_code
fetch('address.country_code')
end
##
# Produces a long (alpha-3) ISO 3166 country code.
#
# @return [String]
#
# @example
# Faker::Address.country_code_long #=> "ITA"
#
# @faker.version 0.3.0
def country_code_long
fetch('address.country_code_long')
end
##
# Produces a latitude.
#
# @return [Float]
#
# @example
# Faker::Address.latitude #=> -58.17256227443719
#
# @faker.version 1.0.0
def latitude
((rand * 180) - 90).to_f
end
##
# Produces a longitude.
#
# @return [Float]
#
# @example
# Faker::Address.longitude #=> -156.65548382095133
#
# @faker.version 1.0.0
def longitude
((rand * 360) - 180).to_f
end
##
# Produces a full address.
#
# @return [String]
#
# @example
# Faker::Address.full_address
# #=> "282 Kevin Brook, Imogeneborough, CA 58517"
#
# @faker.version 0.3.0
def full_address
parse('address.full_address')
end
##
# Produces Address hash of required fields
#
# @return [Hash]
#
# @example
# Faker::Address.full_address_as_hash(:longitude,
# :latitude,
# :country_name_to_code,
# country_name_to_code: {name: 'united_states'})
# #=> {:longitude=>-101.74428917174603, :latitude=>-37.40056749089944, :country_name_to_code=>"US"}
#
# Faker::Address.full_address_as_hash(:full_address)
# #=> {:full_address=>"87635 Rice Street, Lake Brentonton, OR 61896-5968"}
#
# Faker::Address.full_address_as_hash(:city, :time_zone)
# #=> {:city=>"East Faustina", :time_zone=>"America/Mexico_City"}
#
# Faker::Address.full_address_as_hash(:street_address, street_address: {include_secondary: true})
# #=> {:street_address=>"29423 Kenneth Causeway Suite 563"}
#
# @faker.version 2.13.0
def full_address_as_hash(*attrs, **attrs_params)
attrs.map!(&:to_sym)
attrs_params.transform_keys!(&:to_sym)
attrs.map do |attr|
{ "#{attr}": attrs_params[attr] ? send(attr, **attrs_params[attr]) : send(attr) }
end.reduce({}, :merge)
end
end
end
end
| ruby | MIT | a4d5e503edda970fc085e942018ee235622bfb11 | 2026-01-04T15:37:50.353881Z | false |
faker-ruby/faker | https://github.com/faker-ruby/faker/blob/a4d5e503edda970fc085e942018ee235622bfb11/lib/faker/default/house.rb | lib/faker/default/house.rb | # frozen_string_literal: true
module Faker
class House < Base
class << self
##
# Produces the name of a piece of furniture.
#
# @return [String]
#
# @example
# Faker::House.furniture #=> "chair"
#
# @faker.version 1.9.2
def furniture
fetch('house.furniture')
end
##
# Produces the name of a room in a house.
#
# @return [String]
#
# @example
# Faker::House.room #=> "kitchen"
#
# @faker.version 1.9.2
def room
fetch('house.rooms')
end
end
end
end
| ruby | MIT | a4d5e503edda970fc085e942018ee235622bfb11 | 2026-01-04T15:37:50.353881Z | false |
faker-ruby/faker | https://github.com/faker-ruby/faker/blob/a4d5e503edda970fc085e942018ee235622bfb11/lib/faker/default/esport.rb | lib/faker/default/esport.rb | # frozen_string_literal: true
module Faker
class Esport < Base
class << self
##
# Produces the name of a professional eSports player.
#
# @return [String]
#
# @example
# Faker::Esport.player #=> "Crimsix"
#
# @faker.version 1.7.0
def player
fetch('esport.players')
end
##
# Produces the name of an eSports team.
#
# @return [String]
#
# @example
# Faker::Esport.team #=> "CLG"
#
# @faker.version 1.7.0
def team
fetch('esport.teams')
end
##
# Produces the name of an eSports league.
#
# @return [String]
#
# @example
# Faker::Esport.league #=> "IEM"
#
# @faker.version 1.7.0
def league
fetch('esport.leagues')
end
##
# Produces the name of an eSports event.
#
# @return [String]
#
# @example
# Faker::Esport.event #=> "ESL Cologne"
#
# @faker.version 1.7.0
def event
fetch('esport.events')
end
##
# Produces the name of a game played as an eSport.
#
# @return [String]
#
# @example
# Faker::Esport.game #=> "Dota 2"
#
# @faker.version 1.7.0
def game
fetch('esport.games')
end
end
end
end
| ruby | MIT | a4d5e503edda970fc085e942018ee235622bfb11 | 2026-01-04T15:37:50.353881Z | false |
faker-ruby/faker | https://github.com/faker-ruby/faker/blob/a4d5e503edda970fc085e942018ee235622bfb11/lib/faker/default/json.rb | lib/faker/default/json.rb | # frozen_string_literal: true
module Faker
class Json < Base
require 'json'
class << self
##
# Produces a random simple JSON formatted string.
#
# @param width [Integer] Specifies the number of key-value pairs.
# @param options [Hash] Specifies a Faker gem class to use for keys and for values, respectably. options_hash = {key: Class.method, value: Class.method}
# @return [Hash{String => String}]
#
# @example
# Faker::Json.shallow_json(width: 3, options: { key: 'RockBand.name', value: 'Seinfeld.quote' }) # =>
# {"Parliament Funkadelic":"They're real, and they're spectacular.",
# "Fleetwood Mac":"I'm not a lesbian. I hate men, but I'm not a lesbian.",
# "The Roots":"It became very clear to me sitting out there today that every decision
# I've made in my entire life has been wrong. My life is the complete opposite of everything
# I want it to be. Every instinct I have, in every aspect of life, be it something to wear,
# something to eat - it's all been wrong."}
#
# @faker.version 1.9.2
def shallow_json(width: 3, options: { key: 'Name.first_name', value: 'Name.first_name' })
options[:key] = "Faker::#{options[:key]}"
options[:value] = "Faker::#{options[:value]}"
hash = build_shallow_hash(width, options)
JSON.generate(hash)
end
##
# Produces a random nested JSON formatted string that can take JSON as an additional argument.
#
# @param json [Hash{String => String}] Specifies a Json.shallow_json and uses its keys as keys of the nested JSON.
# @param width [Integer] Specifies the number of nested key-value pairs.
# @param options [Hash] Specifies a Faker gem class to use for nested keys and for values, respectably. options_hash = {key: Class.method, value: Class.method}
# @return [Hash{String => String}]
#
# @example
# json = Faker::Json.shallow_json(width: 3, options: { key: 'Name.first_name', value: 'Name.last_name' })
# puts json # =>
# {"Alisha":"Olson","Everardo":"DuBuque","Bridgette":"Turner"}
#
# json2 = Faker::Json.add_depth_to_json(json: json, width: 2, options: { key: 'Name.first_name', value: 'Name.last_name' })
# puts json2 # =>
# {"Alisha":{"Daisy":"Trantow","Oda":"Haag"},
# "Everardo":{"Javier":"Marvin","Eliseo":"Schuppe"},
# "Bridgette":{"Jorge":"Kertzmann","Lelah":"MacGyver"}}
#
# json3 = Faker::Json.add_depth_to_json(json: json2, width: 4, options: { key: 'Name.first_name', value: 'Name.last_name' })
# puts json3 # =>
# {"Alisha":
# {"Daisy":
# {"Bulah":"Wunsch","Cristian":"Champlin","Lester":"Bartoletti","Greg":"Jacobson"},
# "Oda":
# {"Salvatore":"Kuhlman","Aubree":"Okuneva","Larry":"Schmitt","Velva":"Gibson"}},
# "Everardo":
# {"Javier":
# {"Eduardo":"Orn","Laila":"Kub","Thad":"Legros","Dion":"Wilderman"},
# "Eliseo":
# {"Olin":"Hilpert","Marisa":"Greenfelder","Karlee":"Schmitt","Judd":"Larkin"}},
# "Bridgette":
# {"Jorge":
# {"Eloy":"Pfeffer","Kody":"Hansen","Paxton":"Lubowitz","Abe":"Lesch"},
# "Lelah":
# {"Rick":"Wiza","Bonita":"Bayer","Gardner":"Auer","Felicity":"Abbott"}}}
#
# @faker.version 1.9.2
def add_depth_to_json(json: shallow_json, width: 3, options: { key: 'Name.first_name', value: 'Name.first_name' })
options[:key] = "Faker::#{options[:key]}"
options[:value] = "Faker::#{options[:value]}"
hash = JSON.parse(json)
hash.each_key do |key|
add_hash_to_bottom(hash, [key], width, options)
end
JSON.generate(hash)
end
private
def build_shallow_hash(width, options)
key = options[:key]
value = options[:value]
hash = {}
width.times do
hash[eval(key)] = eval(value)
end
hash
end
def add_hash_to_bottom(hash, key_array, width, options)
key_string = build_keys_from_array(key_array)
if eval("hash#{key_string}").is_a?(::Hash)
eval("hash#{key_string}").each_key do |key|
key_array << key
add_hash_to_bottom(hash, key_array, width, options)
end
else
add_hash(key_array, hash, width, options)
key_array.pop
end
end
def add_hash(key_array, hash, width, options)
string_to_eval = 'hash'.dup
key_array.length.times do |index|
string_to_eval << "['#{key_array[index]}']"
end
string_to_eval << " = #{build_shallow_hash(width, options)}"
eval(string_to_eval)
hash
end
def build_keys_from_array(key_array)
key_string = ''.dup
key_array.each do |value|
key_string << "['#{value}']"
end
key_string
end
end
end
end
| ruby | MIT | a4d5e503edda970fc085e942018ee235622bfb11 | 2026-01-04T15:37:50.353881Z | false |
faker-ruby/faker | https://github.com/faker-ruby/faker/blob/a4d5e503edda970fc085e942018ee235622bfb11/lib/faker/default/avatar.rb | lib/faker/default/avatar.rb | # frozen_string_literal: true
module Faker
class Avatar < Base
class << self
# @private
SUPPORTED_FORMATS = %w[png jpg bmp].freeze
##
# Produces a URL for an avatar from robohash.org
#
# @param slug [String, nil]
# @param size [String] image size in pixels, in the format of 'AxB'
# @param format [String] The image file format
# @param set [String] The avatar set to use
# @param bgset [String, nil] The background set to use
# @return [String] A robohash.org URL
#
# @example
# Faker::Avatar.image
# #=> "https://robohash.org/sitsequiquia.png?size=300x300&set=set1"
# @example
# Faker::Avatar.image(slug: "my-own-slug")
# #=> "https://robohash.org/my-own-slug.png?size=300x300&set=set1"
# @example
# Faker::Avatar.image(slug: "my-own-slug", size: "50x50")
# #=> "https://robohash.org/my-own-slug.png?size=50x50&set=set1"
# @example
# Faker::Avatar.image(slug: "my-own-slug", size: "50x50", format: "jpg")
# #=> "https://robohash.org/my-own-slug.jpg?size=50x50&set=set1"
# @example
# Faker::Avatar.image(slug: "my-own-slug", size: "50x50", format: "bmp")
# #=> "https://robohash.org/my-own-slug.bmp?size=50x50&set=set1"
# @example
# Faker::Avatar.image(slug: "my-own-slug", size: "50x50", format: "bmp", set: "set1", bgset: "bg1")
# #=> "https://robohash.org/my-own-slug.bmp?size=50x50&set=set1&bgset=bg1"
#
# @faker.version 1.4.3
def image(slug: nil, size: '300x300', format: 'png', set: 'set1', bgset: nil)
raise ArgumentError, 'Size should be specified in format 300x300' unless size =~ /^[0-9]+x[0-9]+$/
raise ArgumentError, "Supported formats are #{SUPPORTED_FORMATS.join(', ')}" unless SUPPORTED_FORMATS.include?(format)
slug ||= Faker::Lorem.words.join
bgset_query = "&bgset=#{bgset}" if bgset
"https://robohash.org/#{slug}.#{format}?size=#{size}&set=#{set}#{bgset_query}"
end
end
end
end
| ruby | MIT | a4d5e503edda970fc085e942018ee235622bfb11 | 2026-01-04T15:37:50.353881Z | false |
faker-ruby/faker | https://github.com/faker-ruby/faker/blob/a4d5e503edda970fc085e942018ee235622bfb11/lib/faker/default/bank.rb | lib/faker/default/bank.rb | # frozen_string_literal: true
module Faker
class Bank < Base
flexible :bank
class << self
##
# Produces a bank account number.
#
# @param digits [Integer] Number of digits that the generated account number should have.
# @return [String]
#
# @example
# Faker::Bank.account_number #=> 6738582379
# Faker::Bank.account_number(digits: 13) #=> 673858237902
#
# @faker.version 1.9.1
def account_number(digits: 10)
Array.new(digits) { rand(10) }.join
end
##
# Produces a bank iban number.
#
# @param country_code [String, nil] Specifies what country prefix is used to generate the iban code. Providing `nil` will use a random country.
# @return [String]
#
# @example
# Faker::Bank.iban #=> "GB76DZJM33188515981979"
# Faker::Bank.iban(country_code: "be") #=> "BE6375388567752043"
# Faker::Bank.iban(country_code: nil) #=> "DE45186738071857270067"
#
# @faker.version 1.7.0
def iban(country_code: 'GB')
# Each country has its own format for bank accounts
# Many of them use letters in certain parts of the account
# Using regex patterns we can create virtually any type of bank account
country_code ||= iban_country_code
begin
pattern = fetch("bank.iban_details.#{country_code.downcase}.bban_pattern")
rescue I18n::MissingTranslationData
raise ArgumentError, "Could not find iban details for #{country_code}"
end
# Use Faker::Base.regexify for creating a sample from bank account format regex
account = Base.regexify(/#{pattern}/)
# Add country code and checksum to the generated account to form valid IBAN
country_code.upcase + iban_checksum(country_code, account) + account
end
##
# Produces the ISO 3166 code of a country that uses the IBAN system.
#
# @return [String]
#
# @example
# Faker::Bank.iban_country_code #=> "CH"
#
# @faker.version next
def iban_country_code
sample(translate('faker.bank.iban_details').keys).to_s.upcase
end
##
# Produces a bank name.
#
# @return [String]
#
# @example
# Faker::Bank.name #=> "ABN AMRO CORPORATE FINANCE LIMITED"
#
# @faker.version 1.7.0
def name
fetch('bank.name')
end
##
# Produces a routing number.
#
# @return [String]
#
# @example
# Faker::Bank.routing_number #=> "729343831"
#
# @faker.version 1.9.1
def routing_number
valid_routing_number
end
##
# Produces a valid routing number.
#
# @return [String]
#
# @example
# Faker::Bank.routing_number #=> "729343831"
#
# @faker.version 1.9.1
def routing_number_with_format
compile_fraction(valid_routing_number)
end
##
# Produces a swift / bic number.
#
# @return [String]
#
# @example
# Faker::Bank.swift_bic #=> "AAFMGB21"
#
# @faker.version 1.7.0
def swift_bic
fetch('bank.swift_bic')
end
##
# Produces an Australian BSB (Bank-State-Branch) number
#
# @return [String]
#
# @example
# Faker::Bank.bsb_number
# #=> "036616"
#
# @faker.version 2.13.0
def bsb_number
compile_bsb_number
end
private
def checksum(num_string)
num_array = num_string.chars.map(&:to_i)
(
7 * (num_array[0] + num_array[3] + num_array[6]) +
3 * (num_array[1] + num_array[4] + num_array[7]) +
9 * (num_array[2] + num_array[5])
) % 10
end
def compile_routing_number
digit_one_two = %w[00 01 02 03 04 05 06 07 08 09 10 11 12]
((21..32).to_a + (61..72).to_a + [80]).each { |x| digit_one_two << x.to_s }
digit_one_two.sample + rand_numstring + rand_numstring + rand_numstring + rand_numstring + rand_numstring + rand_numstring + rand_numstring
end
def compile_bsb_number
digit_one_two = %w[01 03 06 08 11 12 73 76 78 30]
state = (2..7).to_a.map(&:to_s).sample
digit_one_two.sample + state + rand_numstring + rand_numstring + rand_numstring
end
# Calculates the mandatory checksum in 3rd and 4th characters in IBAN format
# source: https://en.wikipedia.org/wiki/International_Bank_Account_Number#Generating_IBAN_check_digits
def iban_checksum(country_code, account)
# Converts letters to numbers according the iban rules, A=10..Z=35
account_to_number = "#{account}#{country_code}00".upcase.chars.map do |d|
d =~ /[A-Z]/ ? (d.ord - 55).to_s : d
end.join.to_i
# This is the correct answer to (iban_to_num + checksum) % 97 == 1
checksum = 98 - (account_to_number % 97)
# Use leftpad to make the size always to 2
checksum.to_s.rjust(2, '0')
end
def valid_routing_number
routing_number = compile_routing_number
checksum = checksum(routing_number)
return routing_number if valid_checksum?(routing_number, checksum)
routing_number[0..7] + checksum.to_s
end
def valid_checksum?(routing_number, checksum)
routing_number[8].to_i == checksum
end
def compile_fraction(routing_num)
prefix = (1..50).to_a.map(&:to_s).sample
numerator = routing_num.chars[5..8].join.to_i.to_s
denominator = routing_num.chars[0..4].join.to_i.to_s
"#{prefix}-#{numerator}/#{denominator}"
end
def rand_numstring
(0..9).to_a.map(&:to_s).sample
end
end
end
end
| ruby | MIT | a4d5e503edda970fc085e942018ee235622bfb11 | 2026-01-04T15:37:50.353881Z | false |
faker-ruby/faker | https://github.com/faker-ruby/faker/blob/a4d5e503edda970fc085e942018ee235622bfb11/lib/faker/default/electrical_components.rb | lib/faker/default/electrical_components.rb | # frozen_string_literal: true
module Faker
class ElectricalComponents < Base
flexible :electrical_components
class << self
##
# Produces an active electrical component.
#
# @return [String]
#
# @example
# Faker::ElectricalComponents.active #=> "Transistor"
#
# @faker.version 1.9.0
def active
fetch('electrical_components.active')
end
##
# Produces a passive electrical component.
#
# @return [String]
#
# @example
# Faker::ElectricalComponents.passive #=> "Resistor"
#
# @faker.version 1.9.0
def passive
fetch('electrical_components.passive')
end
##
# Produces an electromechanical electrical component.
#
# @return [String]
#
# @example
# Faker::ElectricalComponents.electromechanical #=> "Toggle Switch"
#
# @faker.version 1.9.0
def electromechanical
fetch('electrical_components.electromechanical')
end
end
end
end
| ruby | MIT | a4d5e503edda970fc085e942018ee235622bfb11 | 2026-01-04T15:37:50.353881Z | false |
faker-ruby/faker | https://github.com/faker-ruby/faker/blob/a4d5e503edda970fc085e942018ee235622bfb11/lib/faker/default/alphanumeric.rb | lib/faker/default/alphanumeric.rb | # frozen_string_literal: true
module Faker
class Alphanumeric < Base
##
# List of characters allowed for alphanumeric strings
# @private
ALPHANUMS = LLetters + Numbers
class << self
##
# Produces a random string of alphabetic characters (no digits)
#
# @param number [Integer] The length of the string to generate
#
# @return [String]
#
# @example
# Faker::Alphanumeric.alpha(number: 10) #=> "zlvubkrwga"
#
# @faker.version 1.9.2
def alpha(number: 32)
char_count = resolve(number)
return '' if char_count.to_i < 1
Array.new(char_count) { sample(self::LLetters) }.join
end
##
# Produces a random string of alphanumeric characters
#
# @param number [Integer] The number of characters to generate
# @param min_alpha [Integer] The minimum number of alphabetic to add to the string
# @param min_numeric [Integer] The minimum number of numbers to add to the string
#
# @return [String]
#
# @example
# Faker::Alphanumeric.alphanumeric(number: 10) #=> "3yfq2phxtb"
# @example
# Faker::Alphanumeric.alphanumeric(number: 10, min_alpha: 3) #=> "3yfq2phxtb"
# @example
# Faker::Alphanumeric.alphanumeric(number: 10, min_alpha: 3, min_numeric: 3) #=> "3yfq2phx8b"
#
# @faker.version 2.1.3
def alphanumeric(number: 32, min_alpha: 0, min_numeric: 0)
char_count = resolve(number)
return '' if char_count.to_i < 1
raise ArgumentError, 'min_alpha must be greater than or equal to 0' if min_alpha&.negative?
raise ArgumentError, 'min_numeric must be greater than or equal to 0' if min_numeric&.negative?
return Array.new(char_count) { sample(ALPHANUMS) }.join if min_alpha.zero? && min_numeric.zero?
raise ArgumentError, 'min_alpha + min_numeric must be <= number' if min_alpha + min_numeric > char_count
random_count = char_count - min_alpha - min_numeric
alphas = Array.new(min_alpha) { sample(self::LLetters) }
numbers = Array.new(min_numeric) { sample(self::Numbers) }
randoms = Array.new(random_count) { sample(ALPHANUMS) }
combined = alphas + numbers + randoms
shuffle!(combined).join
end
end
end
end
| ruby | MIT | a4d5e503edda970fc085e942018ee235622bfb11 | 2026-01-04T15:37:50.353881Z | false |
faker-ruby/faker | https://github.com/faker-ruby/faker/blob/a4d5e503edda970fc085e942018ee235622bfb11/lib/faker/default/color.rb | lib/faker/default/color.rb | # frozen_string_literal: true
module Faker
class Color < Base
class << self
LIGHTNESS_LOOKUP = {
light: 0.8,
dark: 0.2
}.freeze
##
# Produces a hex color code.
# Clients are able to specify the hue, saturation, or lightness of the required color.
# Alternatively a client can simply specify that they need a light or dark color.
#
# @param args [Hash, Symbol] Allows the client to specify what color should be return
#
# @return [String]
#
# @example
# Faker::Color.hex_color #=> "#31a785"
# @example
# Faker::Color.hex_color(hue: 118, saturation: 1, lightness: 0.53) #=> "#048700"
# @example
# Faker::Color.hex_color(:light) #=> "#FFEE99"
# @example
# Faker::Color.hex_color(:dark) #=> "#665500"
#
# @faker.version next
def hex_color(args = nil)
hsl_hash = {}
hsl_hash = { lightness: LIGHTNESS_LOOKUP[args] } if %i[dark light].include?(args)
hsl_hash = args if args.is_a?(Hash)
hsl_to_hex(hsl_color(**hsl_hash))
end
##
# Produces the name of a color.
#
# @return [String]
#
# @example
# Faker::Color.color_name #=> "yellow"
#
# @faker.version 1.6.2
def color_name
fetch('color.name')
end
# @private
def single_rgb_color
sample((0..255).to_a)
end
##
# Produces an array of integers representing an RGB color.
#
# @return [Array(Integer, Integer, Integer)]
#
# @example
# Faker::Color.rgb_color #=> [54, 233, 67]
#
# @faker.version 1.5.0
def rgb_color
Array.new(3) { single_rgb_color }
end
##
# Produces an array of floats representing an HSL color.
# The array is in the form of `[hue, saturation, lightness]`.
#
# @param hue [FLoat] Optional value to use for hue
# @param saturation [Float] Optional value to use for saturation
# @param lightness [Float] Optional value to use for lightness
# @return [Array(Float, Float, Float)]
#
# @example
# Faker::Color.hsl_color #=> [69.87, 0.66, 0.3]
# @example
# Faker::Color.hsl_color(hue: 70, saturation: 0.5, lightness: 0.8) #=> [70, 0.5, 0.8]
# @example
# Faker::Color.hsl_color(hue: 70) #=> [70, 0.66, 0.6]
# @example
# Faker::Color.hsl_color(saturation: 0.2) #=> [54, 0.2, 0.3]
# @example
# Faker::Color.hsl_color(lightness: 0.6) #=> [69.87, 0.66, 0.6]
#
# @faker.version next
def hsl_color(hue: nil, saturation: nil, lightness: nil)
valid_hue = hue || sample((0..360).to_a)
valid_saturation = saturation&.clamp(0, 1) || rand.round(2)
valid_lightness = lightness&.clamp(0, 1) || rand.round(2)
[valid_hue, valid_saturation, valid_lightness]
end
##
# Produces an array of floats representing an HSLA color.
# The array is in the form of `[hue, saturation, lightness, alpha]`.
#
# @return [Array(Float, Float, Float, Float)]
#
# @example
# Faker::Color.hsla_color #=> [154.77, 0.36, 0.9, 0.2]
#
# @faker.version 1.5.0
def hsla_color
hsl_color << rand.round(1)
end
private
##
# Produces a hex code representation of an HSL color
#
# @param a_hsl_color [Array(Float, Float, Float)] The array that represents the HSL color
#
# @return [String]
#
# @example
# hsl_to_hex([50, 100,80]) #=> #FFEE99
#
# @see https://en.wikipedia.org/wiki/HSL_and_HSV#HSL_to_RGB
# @see https://github.com/jpmckinney/color-generator/blob/master/lib/color-generator.rb
#
def hsl_to_hex(a_hsl_color)
h, s, l = a_hsl_color
c = (1 - (2 * l - 1).abs) * s
h_prime = h / 60
x = c * (1 - (h_prime % 2 - 1).abs)
m = l - 0.5 * c
rgb = case h_prime.to_i
when 0 # 0 <= H' < 1
[c, x, 0]
when 1 # 1 <= H' < 2
[x, c, 0]
when 2 # 2 <= H' < 3
[0, c, x]
when 3 # 3 <= H' < 4
[0, x, c]
when 4 # 4 <= H' < 5
[x, 0, c]
else # 5 <= H' < 6
[c, 0, x]
end.map { |value| ((value + m) * 255).round }
format('#%02x%02x%02x', rgb[0], rgb[1], rgb[2])
end
end
end
end
| ruby | MIT | a4d5e503edda970fc085e942018ee235622bfb11 | 2026-01-04T15:37:50.353881Z | false |
faker-ruby/faker | https://github.com/faker-ruby/faker/blob/a4d5e503edda970fc085e942018ee235622bfb11/lib/faker/default/app.rb | lib/faker/default/app.rb | # frozen_string_literal: true
module Faker
class App < Base
class << self
##
# Produces an app name.
#
# @return [String]
#
# @example
# Faker::App.name #=> "Treeflex"
#
# @faker.version 1.4.3
def name
fetch('app.name')
end
##
# Produces a version string.
#
# @return [String]
#
# @example
# Faker::App.version #=> "1.85"
#
# @faker.version 1.4.3
def version
parse('app.version')
end
##
# Produces the name of an app's author.
#
# @return [String]
#
# @example
# Faker::App.author #=> "Daphne Swift"
#
# @faker.version 1.4.3
def author
parse('app.author')
end
##
# Produces a String representing a semantic version identifier.
#
# @param major [Integer, Range] An integer to use or a range to pick the integer from.
# @param minor [Integer, Range] An integer to use or a range to pick the integer from.
# @param patch [Integer, Range] An integer to use or a range to pick the integer from.
# @return [String]
#
# @example
# Faker::App.semantic_version #=> "3.2.5"
# @example
# Faker::App.semantic_version(major: 42) #=> "42.5.2"
# @example
# Faker::App.semantic_version(minor: 100..101) #=> "42.100.4"
# @example
# Faker::App.semantic_version(patch: 5..6) #=> "7.2.6"
#
# @faker.version 1.4.3
def semantic_version(major: 0..9, minor: 0..9, patch: 1..9)
[major, minor, patch].map { |chunk| sample(Array(chunk)) }.join('.')
end
end
end
end
| ruby | MIT | a4d5e503edda970fc085e942018ee235622bfb11 | 2026-01-04T15:37:50.353881Z | false |
faker-ruby/faker | https://github.com/faker-ruby/faker/blob/a4d5e503edda970fc085e942018ee235622bfb11/lib/faker/default/greek_philosophers.rb | lib/faker/default/greek_philosophers.rb | # frozen_string_literal: true
module Faker
class GreekPhilosophers < Base
class << self
##
# Produces the name of a Greek philosopher.
#
# @return [String]
#
# @example
# Faker::GreekPhilosophers.name #=> "Socrates"
#
# @faker.version 1.9.0
def name
fetch('greek_philosophers.names')
end
##
# Produces a quote from a Greek philosopher.
#
# @return [String]
#
# @example
# Faker::GreekPhilosophers.quote #=> "Only the educated are free."
#
# @faker.version 1.9.0
def quote
fetch('greek_philosophers.quotes')
end
end
end
end
| ruby | MIT | a4d5e503edda970fc085e942018ee235622bfb11 | 2026-01-04T15:37:50.353881Z | false |
faker-ruby/faker | https://github.com/faker-ruby/faker/blob/a4d5e503edda970fc085e942018ee235622bfb11/lib/faker/default/military.rb | lib/faker/default/military.rb | # frozen_string_literal: true
module Faker
class Military < Base
class << self
##
# Produces a rank in the U.S. Army.
#
# @return [String]
#
# @example
# Faker::Military.army_rank #=> "Staff Sergeant"
#
# @faker.version 1.9.0
def army_rank
fetch('military.army_rank')
end
##
# Produces a rank in the U.S. Marines.
#
# @return [String]
#
# @example
# Faker::Military.marines_rank #=> "Gunnery Sergeant"
#
# @faker.version 1.9.0
def marines_rank
fetch('military.marines_rank')
end
##
# Produces a rank in the U.S. Navy.
#
# @return [String]
#
# @example
# Faker::Military.navy_rank #=> "Seaman"
#
# @faker.version 1.9.0
def navy_rank
fetch('military.navy_rank')
end
##
# Produces a rank in the U.S. Air Force.
#
# @return [String]
#
# @example
# Faker::Military.air_force_rank #=> "Captain"
#
# @faker.version 1.9.0
def air_force_rank
fetch('military.air_force_rank')
end
##
# Produces a rank in the U.S. Space Force.
#
# @return [String]
#
# @example
# Faker::Military.space_force_rank #=> "Senior Enlisted Advisor of the Space Force"
#
# @faker.version next
def space_force_rank
fetch('military.space_force_rank')
end
##
# Produces a rank in the U.S. Coast Guard
#
# @return [String]
#
# @example
# Faker::Military.coast_guard_rank #=> "Master Chief Petty Officer of the Coast Guard"
#
# @faker.version next
def coast_guard_rank
fetch('military.coast_guard_rank')
end
##
# Produces a U.S. Department of Defense Paygrade.
#
# @return [String]
#
# @example
# Faker::Military.dod_paygrade #=> "E-6"
#
# @faker.version 1.9.0
def dod_paygrade
fetch('military.dod_paygrade')
end
end
end
end
| ruby | MIT | a4d5e503edda970fc085e942018ee235622bfb11 | 2026-01-04T15:37:50.353881Z | false |
faker-ruby/faker | https://github.com/faker-ruby/faker/blob/a4d5e503edda970fc085e942018ee235622bfb11/lib/faker/default/nation.rb | lib/faker/default/nation.rb | # frozen_string_literal: true
module Faker
class Nation < Base
flexible :nation
class << self
##
# Produces a random nationality.
#
# @return [String]
#
# @example
# Faker::Nation.nationality #=> "Nepalese"
#
# @faker.version 1.9.0
def nationality
fetch('nation.nationality')
end
##
# Produces a random national flag emoji.
#
# @return [String]
#
# @example
# Faker::Nation.flag #=> "🇫🇮"
#
# @faker.version 1.9.0
def flag
sample(translate('faker.nation.flag')).pack('C*').force_encoding('utf-8')
end
##
# Produces a random national language.
#
# @return [String]
#
# @example
# Faker::Nation.language #=> "Nepali"
#
# @faker.version 1.9.0
def language
fetch('nation.language')
end
##
# Produces a random capital city.
#
# @return [String]
#
# @example
# Faker::Nation.capital_city #=> "Kathmandu"
#
# @faker.version 1.9.0
def capital_city
fetch('nation.capital_city')
end
##
# Produces a random national sport.
#
# @return [String]
#
# @example
# Faker::Nation.national_sport #=> "dandi biyo"
#
# @faker.version 1.9.0
def national_sport
fetch('team.sport')
end
end
end
end
| ruby | MIT | a4d5e503edda970fc085e942018ee235622bfb11 | 2026-01-04T15:37:50.353881Z | false |
faker-ruby/faker | https://github.com/faker-ruby/faker/blob/a4d5e503edda970fc085e942018ee235622bfb11/lib/faker/default/finance.rb | lib/faker/default/finance.rb | # frozen_string_literal: true
module Faker
class Finance < Base
CREDIT_CARD_TYPES = %i[visa mastercard discover american_express
diners_club jcb switch solo dankort
maestro forbrugsforeningen laser].freeze
MARKET_LIST = %i[nyse nasdaq].freeze
class << self
##
# Produces a random credit card number.
#
# @param types [String] Specific credit card type.
# @return [String]
#
# @example
# Faker::Finance.credit_card #=> "3018-348979-1853"
# Faker::Finance.credit_card(:mastercard) #=> "6771-8921-2291-6236"
# Faker::Finance.credit_card(:mastercard, :visa) #=> "4448-8934-1277-7195"
#
# @faker.version 1.2.0
def credit_card(*types)
types = CREDIT_CARD_TYPES if types.empty?
type = sample(types)
template = numerify(fetch("finance.credit_card.#{type}"))
# calculate the luhn checksum digit
multiplier = 1
luhn_sum = template.gsub(/[^0-9]/, '').chars.reverse.map(&:to_i).inject(0) do |sum, digit|
multiplier = (multiplier == 2 ? 1 : 2)
sum + (digit * multiplier).to_s.chars.map(&:to_i).inject(0) { |digit_sum, cur| digit_sum + cur }
end
# the sum plus whatever the last digit is must be a multiple of 10. So, the
# last digit must be 10 - the last digit of the sum.
luhn_digit = (10 - (luhn_sum % 10)) % 10
template.gsub('L', luhn_digit.to_s)
end
##
# Produces a random vat number.
#
# @param country [String] Two capital letter country code to use for the vat number.
# @return [String]
#
# @example
# Faker::Finance.vat_number #=> "BR38.395.329/2471-83"
# Faker::Finance.vat_number('DE') #=> "DE593306671"
# Faker::Finance.vat_number('ZA') #=> "ZA79494416181"
#
# @faker.version 1.9.2
def vat_number(country: 'BR')
numerify(fetch("finance.vat_number.#{country}"))
rescue I18n::MissingTranslationData
raise ArgumentError, "Could not find vat number for #{country}"
end
def vat_number_keys
translate('faker.finance.vat_number').keys
end
##
# Returns a randomly-selected stock ticker from a specified market.
#
# @param markets [String] The name of the market to choose the ticker from (e.g. NYSE, NASDAQ)
# @return [String]
#
# @example
# Faker::Finance.ticker #=> 'AMZN'
# Faker::Finance.vat_number('NASDAQ') #=> 'GOOG'
#
# @faker.version next
def ticker(*markets)
markets = MARKET_LIST if markets.empty?
market = sample(markets)
fetch("finance.ticker.#{market}")
rescue I18n::MissingTranslationData
raise ArgumentError, "Could not find market named #{market}"
end
##
# Returns a randomly-selected stock market.
#
# @return [String]
#
# @example
# Faker::Finance.stock_market #=> 'NASDAQ'
#
# @faker.version next
def stock_market
fetch('finance.stock_market')
end
##
# Returns a random condominium fiscal code.
#
# @param country [String] Two capital letter country code to use for the condominium fiscal code number.
# @return [String]
#
# @example
# Faker::Finance.condominium_fiscal_code #=> "01234567890"
#
# @faker.version next
def condominium_fiscal_code(country: 'IT')
numerify(fetch("finance.condominium_fiscal_code.#{country}"))
end
end
end
end
| ruby | MIT | a4d5e503edda970fc085e942018ee235622bfb11 | 2026-01-04T15:37:50.353881Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.