passwords_generator 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 15516039b7ba97d451a4c2e0e1733cfdb8e6bed654179b7060c72e0c982f46c4
4
+ data.tar.gz: 1234018f189e97b749d6492891898027ac4f9677a36a0325e8ec83b91408b6dd
5
+ SHA512:
6
+ metadata.gz: f47d015ba01008679ea590d32913856c95c8f536af2f6e56ee3aea440e780378ff08a9d78e43ef49142200ef06bf827786ba1d915c4efc41e0ebdc8784b09bd3
7
+ data.tar.gz: 90b4483e05a0654931c164924d14d5f149cd81e4afabf9719b05db8cea7471c7194f124f18307d88eb7c95f1e08e62b19a7f8fb8d118058fe5395944ca713f2b
data/Gemfile ADDED
@@ -0,0 +1,6 @@
1
+ source "https://rubygems.org"
2
+
3
+ git_source(:github) {|repo_name| "https://github.com/#{repo_name}" }
4
+
5
+ # Specify your gem's dependencies in password_gen_gem.gemspec
6
+ gemspec
data/README.md ADDED
@@ -0,0 +1,120 @@
1
+
2
+
3
+ # PasswordsGenerator
4
+
5
+ Enjoy using 😎
6
+
7
+ ## About
8
+
9
+ Generate human readable and easy to remember passwords
10
+
11
+ ## Installation
12
+
13
+
14
+ ```ruby
15
+ gem build passwords_generator.gemspec
16
+ gem install passwords_generator-0.5.0.gem
17
+ ```
18
+ ## Usage
19
+
20
+ ```bash
21
+ irb(main):001:0> require 'passwords_generator'
22
+ => true
23
+
24
+ > PasswordGenerator.new.generate
25
+ => "SYstdepo"
26
+ ```
27
+
28
+ ## Options
29
+
30
+ - Password length
31
+
32
+ > default: 8
33
+
34
+ ```bash
35
+ > PasswordGenerator.new(length: 3).generate
36
+ => "AWy"
37
+
38
+ > PasswordGenerator.new(length: 20).generate
39
+ => "socieprIncommedozEn1"
40
+ ```
41
+
42
+ - Skip upper case
43
+
44
+ > default: false
45
+ ```bash
46
+ > PasswordGenerator.new(skip_upper_case: true).generate
47
+ => "electrhu"
48
+ ```
49
+
50
+ - Without word
51
+ > default: false
52
+ ```bash
53
+ > PasswordGenerator.new(without_word: true).generate
54
+ => "oFoKusar"
55
+ ```
56
+
57
+ - Skip number
58
+ > default: false
59
+ ```bash
60
+ > PasswordGenerator.new(skip_number: true).generate
61
+ => "JamYgrep"
62
+ ```
63
+
64
+ - Count upper case
65
+ > default: 2
66
+
67
+ ```bash
68
+ > PasswordGenerator.new(count_upper_case: 5).generate
69
+ => "DRIveCOn"
70
+
71
+ ```
72
+
73
+ - Custom dictionary
74
+ > default: nil
75
+
76
+ If you want to use your dictionary to generate passwords, pass the path to the text file to the gem.
77
+ words must be separated by spaces
78
+
79
+ sample.txt
80
+
81
+ > Lorem ipsum dolor sit amet, consectetur adipiscing elit,
82
+ > sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut
83
+ > enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi
84
+ > ut aliquip ex ea commodo consequat. Duis aute irure dolor in
85
+ > reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla
86
+ > pariatur. Excepteur sint occaecat cupidatat non proident, sunt in
87
+ > culpa qui officia deserunt mollit anim id est laborum.
88
+
89
+ ```bash
90
+ > PasswordGenerator.new(custom_dictionary_file: 'sample.txt').generate
91
+ => "LorEMcil"
92
+ ```
93
+
94
+ ## Use many options at once!
95
+ ```bash
96
+ > PasswordGenerator.new(length: 5, skip_upper_case: true).generate
97
+ => "obopy"
98
+ ```
99
+ ```bash
100
+ > PasswordGenerator.new(length: 10, without_word: true, count_upper_case: 9).generate
101
+ => "AXIMORUSEp"
102
+ ```
103
+
104
+ ```bash
105
+ > PasswordGenerator.new(custom_dictionary_file: 'sample.txt', skip_upper_case: true, length: 10, ).generate
106
+ => "ullaad54mo"
107
+ ```
108
+ ## Default settings
109
+ ```ruby
110
+ skip_upper_case: false,
111
+ without_word: false,
112
+ skip_number: false,
113
+ length: 8,
114
+ count_upper_case: 2,
115
+ custom_dictionary_file: nil
116
+ ```
117
+
118
+
119
+
120
+
data/Rakefile ADDED
@@ -0,0 +1,2 @@
1
+ require "bundler/gem_tasks"
2
+ task :default => :spec
data/bin/console ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "passwords_generator"
5
+
6
+ # You can add fixtures and/or initialization code here to make experimenting
7
+ # with your gem easier. You can also use a different console, if you like.
8
+
9
+ # (If you use this, don't forget to add pry to your Gemfile!)
10
+ # require "pry"
11
+ # Pry.start
12
+
13
+ require "irb"
14
+ IRB.start(__FILE__)
data/bin/setup ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,12 @@
1
+ class Dictionary
2
+
3
+ attr_reader :words
4
+
5
+ def initialize file_name
6
+ @words = if file_name.nil?
7
+ File.open("#{File.dirname(__FILE__)}/dictionary.txt") {|file| file.read.split(' ')}
8
+ else
9
+ File.open("#{file_name}") {|file| file.read.split(' ')}
10
+ end
11
+ end
12
+ end
@@ -0,0 +1 @@
1
+ zero midnight yard volume boat belly demand intelligence literacy voice miserable free growth residence apathy majority fast outline degree gas pedal emphasis positive achieve achievement agreement history account recognize accumulation experience charge star hurt black admit concede admission thanks receipt friend get AIDS bitter delay stimulation exchange deal favour performance return production jest play activity solo player cast real advertising version dependence addition speech facility stick formal orthodox glue plaster tape set poison council division executive confession include warning teenager acceptance woman man notice progress lead opponent hardship adviser revolutionary function affair attachment association statement open tissue collection hostility fan shake excitement consensus peasant help support object wind broadcast cabin pilot wing plane alarm egg white beer alcohol consciousness excuse extraterrestrial foreigner similar commitment bond comprehensive allocation compromise lonely distance directory index change height aluminium graduate romantic atmosphere dream ambition shell pardon quantity figure supply speed entertainment game funny parallel ancestor fox animal ankle birthday note program bother response expect expectation restless anxiety share factor flat stroke clothes attract sympathetic appeal seem debut look texture convenience engineer rub paint general date assessment estimate arrest permission spider random wall archive arch fire room argument line desert rise weapon sleeve tank smell garlic tease move provoke moving pack row timetable bow gallery reservoir craftsman painter art silver beg invite view attack battery assembly claim selection far forward runner sport front nuclear tin monstrous strike effort serve care costume culture lawyer draw cute attraction property gold auction sound sign aunt writer command regulation government car bus robot transmission motorist fall supplementary common conscious axis baby carriage nursery heel withdrawal suitcase sphere vote trivial patch band slam deposit failure feast banish tycoon drum fence bar trade basis baseball wrong rational democratic cellar essential infrastructure introduction cell principle foundation club bathtub bathroom wash battlefield resist represent float oppose suit know trail ride depend dare differ match like dominate love owe mind run belong beat host win lack worry drop bill kidney carry testify hold stand posture presence rhythm scramble grace salon wave increase conceive deteriorate sheet friendly start source captivate low absent present critical opposed hot outer salvation late swallow think roar noble native left bad flex turn curve flexible good advantage hook leave mourning shoulder siege engagement improve coffee wine drink prejudice bike offer large contract duck turkey call delivery pill morsel chip snack sting burn sword space cover blast combine approval pest flash obstacle brick forget slab vein mosquito inflate punch depressed blue flush heart muscle scale mass constituency lake appendix flesh guard kettle steam cheek bomb sandwich rib tooth dividend horn album notebook prosper stall loot dull adopt breast cap base avenue end border reward cow stadium ring electronics courage toast bread width shatter smash cereal discovery hiccup rest corruption workshop bulletin summary glimpse light brilliance lip prosecute bring generate introduce import create organize publish disclose update take glass spectrum reception leaflet fragment brother eyebrow review cruel champagne garage center architecture displace roll cluster nerve package cottage nonsense load rabbit pop split operation office counter agency burst wear out fuss buttocks cigarette traffic carbon taxi conspiracy corpse disaster multiply month week request cancel predict card career calm crusade candidate frank wolf sail canvas ceiling able content memory capital execution impulse legend prisoner treat consideration shark wrist sketch waterfall precedent advance register barrel coffin hurl catalogue capture bracket nap ranch white cause nature kill offend pour pit crash fame planet orbit cell phone paper penny core headquarters wheat hemisphere ceremony parade funeral license neck straw necklace throne president champion title reform convert freeze switch role feature provincial hostile systematic poor loud plot chase talkative check cheque urge compound element reaction chemistry king chest main head adoption chorus chop helicopter Bible watch lump church slide film round condition reference quote orange block mayor tribe applaud bang confrontation mud pottery soap clarify acquit cut crack mercy fist bishop clerk smart tick snap customer climb climate cutting time close contact cupboard dress overall belt fool seize train coalition harsh coat code contemporary generation cafe proof knowledge belief judgment laser curl snub fish cold cooperate give tent raise wardrobe settlement rainbow mosaic chord land confront enter appear discover bait comfort comfortable leader memorial recommend transaction business commerce market committee board sense park infect write network compact company pity remunerate competence plaintiff finish perfect complication complex follow module behave constitution understand squeeze accountant calculation hardware menu mouse computing software computer hide design imagine notion concept embryo practical applied sacred personal domestic private definition last harmony coincide terms freedom danger improvement behavior experiment director south federation trust constellation impound battle fit adjust standard normal compliance praise representative link related node draft sanctuary agree product effect doubt courtesy thoughtful TRUE tight structure use infection bin cassette full pollution competition satisfaction race circumstance Europe pupil deny contradiction joystick recovery rule transition convince vehicle sentence fabricate biscuit herb oil pan pot cage partnership cooperative policeman hospitality cord right discipline decorative makeup price clique cotton sofa matter mole offset poll coup voucher brave seminar credit course curriculum direction warrant polite court designer bloody jealous colleague cattle gap wisecrack cunning craft crackpot crevice rotten appetite creep fold creation artist thinker literature credibility creed sailor prosecution record criticism crosswalk bend collapse squash gravel copper snuggle clue cucumber ethnic mug cabinet cup remedy suppress heal lock money damn swear pillow convention tradition reduce amputate crop carve skin fork sale pat sunrise dairy total ballet navy dark favourite style file track dawn anniversary holiday fog shock body hand lot franchise shortage consider expose behead death betray decade resolution classify refuse recession descent decay medal reduction order devote profound well carrot coma default nonremittal fault lemon payment temperature quality god extension censorship debate lace tasty pleasure please pleasant preach rescue challenge limit demonstration destruction thick density reliable describe subject exile bank depression rob commission lineage origin integration merit motif plan functional architect want despair sweet fate break point confine custody discourage weigh decisive hate explode explosion modernize abnormal instrument filter crown dialogue negotiation journal drown break down diet disagree mess difficulty excavation industry proportion decrease diplomatic first-hand management manager soil disability denial unpleasant separation disk dump study negative stop disco offense find incongruous digital consultation treatment contempt spirit mask pie dish disorder case chart quarrel difference neglect dismiss joint undress interrupt disturbance disagreement thesis deter mile aloof trait characteristic spread circulate quarter upset trench butterfly variety deviation even harm work doctor philosophy charter pound dollar goat dog chicken cultivate control contribution gate bell threshold dorm drug image ruin drain opera drama theater curtain pull tap tie diagram fear awful sip dribble drive quit heroin user rehearsal east north west ditch repeat length twilight responsibility obligation house home dynamic past mail world pole relief relaxation accessible tender distinct handy restaurant aid economist boom economics economy value margin bean onion corn building school influence effective egg self ego hip elbow old choose voter current electron hill lift elite banana articulate flag eagle utter glow sentiment pain stress conglomerate empirical authorise blank clear brain witch surround frame meeting favorable invasion restrain settle output acute conclusion terminal survival opposition fuel wrap wrestle mastermind technology concentration enjoy indulge expansion soldier registration plead break in penetrate tempt temptation solid burial entry access ticket twist environment era balance breakdown just ambiguous ambiguity delete error intensify adventure flight leak perfume habit institution admiration respect folk music evening incident trouble eternal estate grounds contrary test screen inspector mine exclude fat sell redeem correspond correspondence proclaim exclusive monopoly justify example illustrate work out practice dominant exercise press show display museum emergency abstract elaborate area anticipation prospect eject spend feel authority expertise reason explain remark graphic exhibition complain explicit apology highway delicate reach society surface outside blackmail deport galaxy glasses lid silk material manufacture side grimace aspect beard fax parameter observation attention fairy miss overlook lose weakness absence sunshine forge illusion distort acquaintance kinship crystal agriculture model trick secure screw knot cream tired blame prefer progressive cower concern bold viable banquet agent toll desire unrest confidence proud cat criminal hen girl bitch queen mother iron ferry conception celebration story fibre character novel fight stuff fill occupy movie producer final fund treasurer convict clay powder sand thumb fastidious particular goal fireplace shoot rifle firefighter strong cousin initial beginning initiative freshman financial salmon aquarium fisherman healthy equip convulsion scene cook fee interest tile meat steward toss deck level stun floor vegetation plant dough spill lily variation chimney soar concentrate family folk conventional second cheese grain salad cheat reckless football trace marathon step boot offensive raid patience power camp impact force index finger exotic chief deer prevent branch spin class shape ball format abandon strength castle accident coal spring wheel skeleton rack hotdog fraud monster relieve straight safe clean dry pure weight exempt release liberty halt frequency original clash refrigerator ally warm terrify medieval facade ice cream ice cherry apple defeat foot smoke official mushroom mold desk seat lamp rage joke choke profit make gallon risk net score top gas meet homosexual regard gear jelly diamond jewel gem sex category health productive mutation genetic exploration zone circle escape cope age abolish eliminate master arise outfit ghostwriter charity talented daughter bless define perform pay distribute thank spare resignation secretion marble glance shine gloom glare frown sticky sink retire happen accompany pass fail goalkeeper departure golf peanut charm bloodshed overeat extort ministry minister catch gradient mark drift rice grandfather grandmother grip hay scrape tip gravity cemetery major high produce green welcome grudge mill traction army background cooperation flock herd organisation fleet troop adult development ensure defend hypothesis direct guide guideline guilt innocent taste water inhabitant haircut hall hammer basket manual cart umbrella glove hang yearn coincidence difficult cash wood nut damage collar harvest harass rush have wear dine afford brown sour steep smooth sharp sensitive complete square deep short weak infinite mature meadow veil governor helmet clearance therapist pile listen rumor grief heat responsible service portion dome moment future reluctance retreat fever highlight extreme handicap interference employ slap pawn pig keep resort tube bubble excavate habitat housewife honor addicted tire basketball platform fool around ward inn enemy firm hut hour husband color embrace giant act face arm humanity comedy hunting safari hunter suffer injury suffering cross theory preoccupation identity identification dialect lighter sick unlawful notorious fantasy projection picture copy huge exemption affect spoil fair jungle pressure flawed temporary tool brush issue jail unlikely momentum tense regular unanimous accurate central inch passive still dead helpless tendency list whole conflict incapable contain double few insurance bay separate needle need person morale single lazy incentive splurge cheap implicit childish virus hell hospital determine flu information recording rare violation consumption monk instinct heir first shot pioneer inquiry ask question dedicate bee indoor insistence fresh establish episode exception college teach lecture education teacher means deficiency abuse coverage policy premium guerrilla rebel rebellion unity news mean purpose intervention inside middle medium translate read spokesperson crossing period bowel fascinate suspicion feeling flood innovation stock reverse speculate detective investment guest physical anger publication exit loop blue jean twitch appointment athlete reporter voyage joy try litigation parachute judicial law judge justice deprive discreet piano child calorie favor lion affinity oven knee stab horse sweater experienced laboratory union maze ignorance ignorant shallow bald soft bare girlfriend secular island site ground landowner name lick theft cathedral tiger great river crowd stage range pumpkin whip endure permanent tension fashion crime grass save store leadership blade leaf thin jump academy resign farewell depart talk leftovers action trustee liability opinion jurisdiction trial verdict key legislation legislature continuation wound minor disappoint disappointment deadly letter hover dictionary licence lie biography revoke beam bulb pastel ignite blonde equal restrict diameter column language context connection soup eavesdrop torch essay fiction small alive accept enthusiasm resident social lend engine housing attic log implication linger strip ridge shaft bench monkey admire relax Sunday misplace sacrifice drawing speaker chin minimum fortune chance trunk timber lunch thrust grand intermediate machinery spell enlarge dimension maid post mail carrier brand reproduce deliver impress guess activate bark enhance weave amuse obscure touch revise develop knit reconcile decide widen presentation father spite cancer mistreat finance exploit falsify laborer construct demonstrate march seal wild seller distributor proposal wedding marriage wife marsh wonder communist grind rally glacier domination chew concrete plastic mathematics equation grow maximum buffet way qualify measure beef pump dressing clinic medicine specimen symptom see conference qualified theme tune partner citizen memorandum learn crew threat attitude outlook refer merchant freighter cruelty deserve fun hypnothize steel wire metal subway city microphone bomber campaign occupation factory minute aware miner mislead distortion mixture cake air solution confusion groan pattern mild routine empire abbey grant coin allowance debt virtue ethics integrity morning breakfast gesture movement motivation motorcycle truck slogan mountain volcano go stir dance skate glide swipe bounce swing migration circulation cinema mobile multimedia mutter contraction composer piece orchestra concert dragon sodium appoint nomination tell channel lane narrow congress hair tongue sickness marine approach tidy requirement thirsty negligence ignore bargain neighbour cool nervous latest report headline night agile retired lost duke owl bat extinct article civilian objective average census relative indirect ordinary genuine unfortunate tough false slow modest public integrated inappropriate other loose raw hard mention warn reputation harmful reactor chain count number foster food approve oak fixture protest dirty stubborn reserve borrow available profession seasonal sea visual eye primary heavy long superior neutral oral diplomat twin senior nose bear leg page critic survivor trainer linear half tray window hole surgeon automatic aviation driver contrast choice mouth satellite agenda liver donor orgy decoration kit expenditure printer scandal overwhelm manage exaggerate revolution obese due possession rate elephant treaty bucket shame palm tract chaos gasp trouser heaven ideal paralyzed uncle parking word drawer member root colon thigh jaw unfair bride detail elapse perforate faint skip reject exceed aisle hallway passage passion graze pasture patent route terrace nationalist nationalism syndrome hesitate pause wage pension royalty rent peace fur punish retiree population hear observer percent insight absolute benefit performer century magazine cycle die allow vertical persist remain porter rider conductor vegetarian virgin slave patient witness consumer worker hero radical personality pin manner staff sweat basic operational dramatic throat telephone photograph camera wording evolution assault human body fitness size shelter physics broken prescription collect pluck photography print chalk bed field mechanism stereotype tablet dismissal organ urine slant arena bury insert mosque sow address put arrangement position braid layout Venus biology flower houseplant fossil weed sculpture credit card panel pen fragrant attractive abundant shower feather looting dive asset poetry concession location extent corner arrow officer party ideology colony pyramid bacon dose part portrait easy orientation charismatic beautiful rich acquisition possibility station stamp tail possible potential pocket swarm flour hierarchy blow application realism sermon priority exact definite precision precede predator horoscope preference racism chauvinist assumption absorption training bake ready prevalence gift conservation jam administration presidency push lobby coerce glory prestige assume imposter mainstream quotation discount chimpanzee crude form prison hostage coach privacy award likely investigation process gradual perception announcement manufacturer professor uniform professional chair technique gain offspring forecast forbid ban throw missile prediction sustain pledge marketing remind launch pitch advocate quota advice suggest owner protection demonstrator pride entertain feed state soul analysis analyst psychology sensation forum publicity riot edition promotion publisher pool drag extract penalty student buy hobby button advertise lay instal install execute nominate earthquake dilemma prey satisfied pursuit problem quiet silence fraction Koran radiation sickness radio radiation X-ray railcar railroad storm rain breed build noise knock rape ecstasy rank preparation reality back new beneficiary mutual appreciate realize tolerate referral compensation document matrix correction recover loss red redundancy polish sugar elegant mirror reflection asylum garbage popular continental national presidential constitutional imperial cultural economic magnetic moral environmental ratio relation relevance faith comment commemorate retain shave relinquish restoration lease tenant fix meal refund repetition regret substitute reproduction answer storage map recycle reptile horror researcher qualification palace community ash immune conservative tolerant pneumonia lung feedback kneel brake constraint result revival revive retailer outlet revenge withdraw remember echo opposite reader reinforce wealth jockey right wing entitlement copyright option fruit rear inflation venture ritual gown rock kitchen suite rotation path road carpet rugby finished flow country countryside undermine salesperson greeting irony moon stroll flavor pray dictate expression strikebreaker frighten spray landscape scheme system scholar session classroom forestry science despise scratch conscience bronze gossip harbor seek coast endorse mystery secretary patrol security visible seed recruit quest transparent gene section bite elect pick assertive vain paradox willpower spontaneous arrogant dignity autonomy export greet perceive humor ear reasonable sensitivity detector discriminate distant barrier scenario sequence series snake waiter established arrange apparatus strict stitch faithful shadow nuance feign embarrassment disgrace cylinder edge bundle bleed protect budge reflect horseshoe beach short circuit jacket shorts deficit abridge injection strap brag prove shrink bush shiver mix ostracize closed temple profile digress pavement symbol meaning important lover velvet flatware plain stool simplicity honest unit sin sister nun sit locate ample magnitude survey slip skilled scan freckle peel omission captain horizon angle killer murder bedroom steak stumble gaffe slippery dip slump slime snail bullet sleep particle berry pony limited packet sample scrap slot compartment village minority fine petty dash smile spot trap snatch kidnap snow serious gregarious ant welfare socialist civilization pudding worm casualty suspect communication wreck prince resource monarch bridge formation shout snarl whisper privilege audience hypothesize accent trance spit sector pepper shed angel divorce divide referee stain expand scatter encourage team waste crouch jet crutch staircase stake haunt stem stable norm sun begin situation safety relationship reliance isolation say declaration formula rung wait lodge constant plagiarize ladder stay pierce muggy miscarriage shareholder sock plug shop straighten strategic wander banner trolley struggle stretch hit kick stunning guitar ribbon conviction emotion vigorous cable tower nest auditor trip fashionable chapter paragraph soak replace suburb brainstorm inspiration evoke indication proper sulphur budget sum overview summer summit superintendent miracle dinner bag prayer cater inspire provide provision shelf pier inhibition overcharge certain excess deputy replacement defendant chocolate swell door shift swop understanding interactive calendar research salt table undertake tactic breathe insist inject eat absorb insure participate musical conversation discuss tree suntan candle duty assignment job bland tax species instruction tear rhetoric television mood disposition pace loan trend strain finger abortion district panic examination will tribute recommendation leash text grateful Mars tragedy theorist slice mist nail layer thread dilute combination thought spine idea brink flourish fling confuse bolt relate bind lean occasion youth reign season clock shy can topple tiptoe frog labour item liberal grave tone knife drill dentist roof place tumble agony torture add tournament doll dealer myth tread transfer transform freight fare transport rubbish fly swim visit rehabilitation jury triangle victory prize gutter truth loyalty vat pipe stomach tumour rotate ivory dozen year day string pair couple tropical color-blind incredible uncertainty reveal vague spy cave underline bottom minimize project unlike unique surprise discrimination thaw continuous lesson ton consolidate global different volunteer artificial live dangerous invisible blind rough crisis frozen premature strange illness unaware folklore promote hilarious nightmare urgency sweep walk interface mechanical useful sigh threaten vacuum valley evaluate worth avant-garde disappear variable variant broccoli vegetable van rocket embark promise poem peak bottle veteran neighborhood winner video compete wake energy active computer virus ghost sight tourist appearance colorful vision singer soprano intention book election ballot exposure bet waist queue lounge hike stride pedestrian cane deprivation war bird guarantee laundry basin password fountain stream vessel acid fluctuation method lifestyle gun cry valid familiar wagon sniff linen extend pigeon wilderness winter hope retirement fade express feminine feminist forest courtship sheep term formulate solve employee studio decline respectable acceptable misery compose wriggle script message offender sausage photocopy annual old age scream amber calf kid boy lamb junior young breeze earthflax earthwax earwax eaux econobox efflux embox enfix epicalyx equinox ex executrix
@@ -0,0 +1,3 @@
1
+ module PasswordsGenerator
2
+ VERSION = "0.5.0"
3
+ end
@@ -0,0 +1,76 @@
1
+ require "passwords_generator/version"
2
+ require "passwords_generator/dictionary.rb"
3
+
4
+ class PasswordGenerator
5
+ VOWELS = [ 'a', 'e', 'i', 'o', 'u', 'y' ]
6
+ CONSOSTANTS = ['b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x']
7
+ DEFAULT_GENERATE_OPTIONS = {
8
+ skip_upper_case: false,
9
+ without_word: false,
10
+ skip_number: false,
11
+ length: 8,
12
+ count_upper_case: 2,
13
+ custom_dictionary_file: nil
14
+ }
15
+
16
+ def initialize(options={})
17
+ @params = DEFAULT_GENERATE_OPTIONS.merge(options)
18
+ @dictionary = Dictionary.new(@params[:custom_dictionary_file]) unless @params[:without_word]
19
+ @password = ''
20
+ end
21
+
22
+ def generate
23
+ @params[:length] < 8 || @params[:without_word] ? generate_without_word : generate_with_word
24
+ unless @params[:skip_upper_case]
25
+ @params[:count_upper_case].times{random_letter_capital}
26
+ end
27
+ @password
28
+ end
29
+
30
+ private
31
+
32
+ def generate_with_word(length = @params[:length])
33
+ if length > 0
34
+ const = length >= 6 ? rand(4..6) : length
35
+ @password << random_word(const)
36
+ generate_with_word(length-const)
37
+ else
38
+ @password
39
+ end
40
+ end
41
+
42
+ def generate_without_word
43
+ @params[:length].times{|number| @password << random_symbol(number) }
44
+ end
45
+
46
+ def random_word(length)
47
+ word = @dictionary.words.sample
48
+ if word.length >= length
49
+ word[0..length-1]
50
+ else
51
+ number_length = length - word.length
52
+ number_length.times{ |i| word << (@params[:skip_number] ? random_symbol(i) : rand(10).to_s)}
53
+ word
54
+ end
55
+ end
56
+
57
+ def random_symbol(number)
58
+ number.even? ? VOWELS.sample : CONSOSTANTS.sample
59
+ end
60
+
61
+ def random_letter_capital
62
+ letter = capital_letter
63
+ if letter[1].nil?
64
+ random_letter_capital
65
+ else
66
+ @password[letter[0]] = letter[1].upcase
67
+ end
68
+ end
69
+
70
+ def capital_letter
71
+ random_index = rand(@password.length - 1)
72
+ random_letter = @password[random_index]
73
+ letter = /[a-z]/.match(random_letter).nil? ? nil : random_letter
74
+ [random_index, letter]
75
+ end
76
+ end
@@ -0,0 +1,24 @@
1
+ # -*- encoding: utf-8 -*-
2
+ $:.push File.expand_path("../lib", __FILE__)
3
+ require "passwords_generator/version"
4
+
5
+ Gem::Specification.new do |s|
6
+ s.name = "passwords_generator"
7
+ s.version = PasswordsGenerator::VERSION
8
+ s.platform = Gem::Platform::RUBY
9
+ s.authors = ["Andrey Morozov"]
10
+ s.email = ["ic3morozov@ya.ru"]
11
+ s.homepage = "https://github.com/adavaika/passwords_generator"
12
+ s.summary = %q{Generate human readable and easy to remember passwords}
13
+ s.description = %q{Generate human readable and easy to remember passwords}
14
+
15
+ s.rubyforge_project = "password_generator"
16
+
17
+ s.files = `git ls-files`.split("\n")
18
+ s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
19
+ s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
20
+ s.require_paths = ["lib"]
21
+
22
+ s.add_development_dependency("rspec", ">= 2.6.0")
23
+ s.add_development_dependency("yard", ">= 0")
24
+ end
metadata ADDED
@@ -0,0 +1,83 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: passwords_generator
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.5.0
5
+ platform: ruby
6
+ authors:
7
+ - Andrey Morozov
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2018-10-15 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: rspec
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: 2.6.0
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: 2.6.0
27
+ - !ruby/object:Gem::Dependency
28
+ name: yard
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - ">="
32
+ - !ruby/object:Gem::Version
33
+ version: '0'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - ">="
39
+ - !ruby/object:Gem::Version
40
+ version: '0'
41
+ description: Generate human readable and easy to remember passwords
42
+ email:
43
+ - ic3morozov@ya.ru
44
+ executables:
45
+ - console
46
+ - setup
47
+ extensions: []
48
+ extra_rdoc_files: []
49
+ files:
50
+ - Gemfile
51
+ - README.md
52
+ - Rakefile
53
+ - bin/console
54
+ - bin/setup
55
+ - lib/passwords_generator.rb
56
+ - lib/passwords_generator/dictionary.rb
57
+ - lib/passwords_generator/dictionary.txt
58
+ - lib/passwords_generator/version.rb
59
+ - passwords_generator.gemspec
60
+ homepage: https://github.com/adavaika/passwords_generator
61
+ licenses: []
62
+ metadata: {}
63
+ post_install_message:
64
+ rdoc_options: []
65
+ require_paths:
66
+ - lib
67
+ required_ruby_version: !ruby/object:Gem::Requirement
68
+ requirements:
69
+ - - ">="
70
+ - !ruby/object:Gem::Version
71
+ version: '0'
72
+ required_rubygems_version: !ruby/object:Gem::Requirement
73
+ requirements:
74
+ - - ">="
75
+ - !ruby/object:Gem::Version
76
+ version: '0'
77
+ requirements: []
78
+ rubyforge_project: password_generator
79
+ rubygems_version: 2.7.6
80
+ signing_key:
81
+ specification_version: 4
82
+ summary: Generate human readable and easy to remember passwords
83
+ test_files: []