Skip to content

Instantly share code, notes, and snippets.

@roktas
Last active August 29, 2015 14:02
Show Gist options
  • Save roktas/aeb4275ad1f9271829c2 to your computer and use it in GitHub Desktop.
Save roktas/aeb4275ad1f9271829c2 to your computer and use it in GitHub Desktop.
#!/usr/bin/ruby
# encoding: utf-8
require 'optparse'
require 'ostruct'
# Generate random names
class Zar # rubocop:disable ClassLength
DEFAULT_LANGUAGE = :auto
DEFAULT_SEPARATOR = '-'
FALLBACK_LANGUAGE = :en
DICTIONARY = {
en: {
adjective: %w(
affectionate
aged
amiable
ancient
arrogant
balmy
barren
benevolent
billowing
bitter
black
blessed
blue
bold
breezy
broken
calm
celestial
charming
cold
combative
composed
condemned
cool
crimson
cyan
damp
dark
delicate
divine
dry
empty
energized
enigmatic
exuberant
falling
floral
flowing
fluffy
fluttering
fragrant
frightened
frosty
fuscia
gentle
greasy
green
grieving
harmonious
hidden
hollow
holy
homeless
icy
indigo
inquisitive
itchy
joyful
jubilant
juicy
khaki
late
limitless
lingering
little
lively
long
lush
magenta
mellow
merciful
merry
mirthful
misty
moonlit
muddy
mysterious
nameless
natural
old
outrageous
pacific
parched
patient
placid
pleasant
poised
polished
proud
purple
purring
quiet
radioactive
red
resilient
restless
rough
scenic
screeching
sensitive
serene
shy
silent
small
snowy
solitary
spacial
sparkling
squealing
stark
still
stunning
talented
tasteless
teal
thoughtless
thriving
throbbing
tranquil
tropical
twilight
undisturbed
unsightly
unwavering
uplifting
violet
voiceless
wandering
warm
wealthy
weathered
whispering
white
wild
wispy
withered
wooden
yellow
young
zealous
),
noun: %w(
abyss
atoll
aurora
autumn
badlands
beach
bird
blue
breeze
briars
brook
bush
butterfly
canopy
canyon
cavern
chasm
cherry
cliff
cloud
cove
crater
creek
cyan
darkness
dawn
desert
dew
dove
dream
drylands
dusk
dust
farm
feather
fern
field
fire
firefly
flower
flowers
fog
foliage
forest
frog
frost
galaxy
garden
geyser
glade
glitter
grass
green
grove
haze
hill
hurricane
iceberg
lagoon
lake
leaf
leaves
magenta
marsh
meadow
mist
moon
morning
moss
mountain
night
oasis
ocean
paper
peak
pebble
pine
plateau
pond
purple
rain
red
reef
reserve
resonance
river
sanctuary
sands
sea
shadow
shape
shelter
silence
sky
smoke
smokescreen
snow
snowflake
sound
spring
star
storm
stream
summer
summit
sun
sunrise
sunset
sunshine
surf
swamp
temple
thorns
thunder
tree
tsunami
tundra
valley
violet
voice
volcano
water
waterfall
wave
wildflower
willow
wind
winds
winter
wood
yellow
)
},
tr: {
adjective: %w(
acayip
alfabetik
analog
anonim
antik
asil
beklenen
belirsiz
benzersiz
bereketli
beyaz
bozuk
bulutsuz
cesur
cezbedici
ciddi
dar
dengesiz
derin
dev
dijital
dik
dogmatik
durgun
egzotik
elastik
engebeli
epik
eski
etnik
fakir
geleneksel
geveze
gizemli
gri
grotesk
hafif
hantal
homojen
huzurlu
ihtiyar
ilahi
ilkel
ince
iri
jenerik
kaotik
kaygan
kederli
kirli
korkutucu
kurak
kusursuz
kutsal
lacivert
lanetli
limitsiz
manyetik
masum
mavi
mekanik
mikro
mistik
monoton
mor
nazik
nemli
nevrotik
olgun
otomatik
parlak
patolojik
pembe
plastik
radyoaktif
ritmik
romantik
senfonik
serin
serseri
sessiz
sihirli
sisli
siyah
sonsuz
tehlikeli
temiz
tombul
tropikal
turuncu
ucuz
ulu
unutulmaz
uyduruk
uzak
uzun
verimsiz
yabani
yapay
yatay
yeni
yitik
yorgun
yuvarlak
zarif
zehirli
zengin
zorlu
),
noun: %w(
ahtapot
akvaryum
asit
ay
aysberg
bakteri
balon
bayram
beyaz
bisiklet
bulmaca
buz
cin
cirit
cumhuriyet
dalgalar
damlalar
dans
dedikodu
deney
deniz
deprem
deve
dikenler
dinozor
dua
duman
efsane
ego
ejderha
embriyo
esinti
fermuar
festival
gece
gergedan
gezegen
girdap
gramofon
gri
hayat
hezeyan
hikaye
horoz
hortum
ikilem
iksir
ilkbahar
jeton
jilet
kader
kahve
kalem
kaos
kar
kaya
kelebek
kent
kertenkele
klarinet
koku
korku
krater
kumsal
kuyu
labirent
lacivert
leblebi
lokomotif
makine
manifesto
mavi
mehtap
melodi
mevsim
meydan
mor
nargile
nehir
nota
nutuk
oda
okyanus
opera
orkide
orman
otlar
ova
oyuncak
papatya
pembe
piyango
portakal
radar
randevu
rapsodi
robot
saatler
sabah
safari
sayfa
semaver
sinek
siyah
sokak
sonbahar
tayfun
telefon
tepe
tespih
tsunami
turuncu
ufuk
uyku
vadi
vapur
volkan
yakamoz
yapraklar
yarasa
yaz
yokluk
zambak
)
}
}
attr_reader :language, :separator, :dictionary, :past
def initialize(option = {})
@language = setup_language(option.fetch(:language, DEFAULT_LANGUAGE))
@separator = option.fetch(:separator, DEFAULT_SEPARATOR)
@past = option[:past] || []
@dictionary = DICTIONARY[@language]
end
def name(repeat = nil, &block)
names = []
(repeat || 1).times do
name = try(&block)
next unless name
names << name
past << name
end
names
end
alias_method :rasgele, :name
class << self
def name(option = {})
new(option).name(option[:repeat])
end
alias_method :rasgele, :name
end
private
def setup_language(langy)
langy = langy.to_sym if langy
if langy.nil? || langy == :auto
auto_language
elsif langy == FALLBACK_LANGUAGE
langy
else
language = valid_language(langy)
fail ArgumentError, "invalid language: #{langy}" unless language
language
end
end
def auto_language
langy =
%w(LC_MESSAGE LANG LANGUAGE LC_CTYPE LC_ALL).map do |locale|
ENV[locale]
end.compact.first
return FALLBACK_LANGUAGE unless langy
valid_language(langy) || FALLBACK_LANGUAGE
end
def valid_language(langy)
DICTIONARY.keys.find { |key| langy.to_s.start_with? key.to_s }
end
def generate
adjective = dictionary[:adjective].sample
while (noun = dictionary[:noun].sample) == adjective; end
[adjective, noun]
end
def build(words)
words.join separator
end
def try
(@combinations ||= dictionary.values.map(&:size).inject(:*)).times do
words = generate
next if block_given? && !yield(words, past)
name = build(words)
next if past.find { |item| item.start_with? name }
return name
end
nil
end
end
def main # rubocop:disable MethodLength
option = OpenStruct.new language: Zar::DEFAULT_LANGUAGE
OptionParser.new do |o|
o.on(
'-l', '-l language',
"language [default: #{Zar::DEFAULT_LANGUAGE}]"
) do |arg|
option.language = arg
end
o.on(
'-d', '-d directory',
'directory to compute past [default: none]'
) do |arg|
unless File.directory? arg
$stderr.puts "No such directory #{arg}"
exit 1
end
option.past =
Dir[File.join(arg, '*')].map do |f|
File.basename(f)
end
end
o.on(
'-s', '-s separator',
"separator between words [default: #{Zar::DEFAULT_SEPARATOR}]"
) do |arg|
option.separator = arg
end
o.on(
'-h', 'show this help'
) do
$stderr.puts o
exit 2
end
o.parse!
end
repeat = nil
if ARGV.size > 0
begin
repeat = Integer(ARGV.shift)
rescue ArgumentError
$stderr.puts 'Repeat count must be an integer; exiting.'
exit 1
end
end
begin
zar = Zar.new(option.marshal_dump)
rescue ArgumentError => err
$stderr.puts err.message
exit 1
end
names = zar.name repeat
puts names.join("\n")
end
main if __FILE__ == $PROGRAM_NAME
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment