Class: Generator
- Inherits:
-
Object
- Object
- Generator
- Defined in:
- lib/spass.rb
Instance Attribute Summary collapse
-
#allowed ⇒ Object
readonly
Returns the value of attribute allowed.
-
#chars ⇒ Object
readonly
Returns the value of attribute chars.
-
#dict ⇒ Object
readonly
Returns the value of attribute dict.
-
#file ⇒ Object
readonly
Returns the value of attribute file.
Instance Method Summary collapse
-
#generate(num_words, options = {}) ⇒ Object
Generate a passphrase with the given number of words.
-
#initialize(file = '/usr/share/dict/words', options = {}) ⇒ Generator
constructor
Create a Generator using the given word dictionary.
-
#random_number ⇒ Object
Return a random number from 0 to 9.
-
#random_word ⇒ Object
Return a random word from the dictionary.
-
#read_dict ⇒ Object
Read a word dictionary from the given file, and return an array of elements that match the allowed regex.
Constructor Details
#initialize(file = '/usr/share/dict/words', options = {}) ⇒ Generator
Create a Generator using the given word dictionary
5 6 7 8 9 10 |
# File 'lib/spass.rb', line 5 def initialize(file='/usr/share/dict/words', ={}) @file = file @allowed = [:allowed] || /^[a-z]+$/ @chars = ([:chars] || 10).to_i @dict = read_dict end |
Instance Attribute Details
#allowed ⇒ Object (readonly)
Returns the value of attribute allowed.
3 4 5 |
# File 'lib/spass.rb', line 3 def allowed @allowed end |
#chars ⇒ Object (readonly)
Returns the value of attribute chars.
3 4 5 |
# File 'lib/spass.rb', line 3 def chars @chars end |
#dict ⇒ Object (readonly)
Returns the value of attribute dict.
3 4 5 |
# File 'lib/spass.rb', line 3 def dict @dict end |
#file ⇒ Object (readonly)
Returns the value of attribute file.
3 4 5 |
# File 'lib/spass.rb', line 3 def file @file end |
Instance Method Details
#generate(num_words, options = {}) ⇒ Object
Generate a passphrase with the given number of words
40 41 42 43 44 45 46 47 48 |
# File 'lib/spass.rb', line 40 def generate(num_words, ={}) words = [] num_words.times do word = random_word word += random_number.to_s if [:digits] words << word end return words.join(' ') end |
#random_number ⇒ Object
Return a random number from 0 to 9
35 36 37 |
# File 'lib/spass.rb', line 35 def random_number rand(10) end |
#random_word ⇒ Object
Return a random word from the dictionary
30 31 32 |
# File 'lib/spass.rb', line 30 def random_word @dict[rand(@dict.count)] end |
#read_dict ⇒ Object
Read a word dictionary from the given file, and return an array of elements that match the allowed regex. Raise an exception if the given dictionary file cannot be found.
15 16 17 18 19 20 21 22 23 24 25 26 27 |
# File 'lib/spass.rb', line 15 def read_dict if !File.file?(@file) raise RuntimeError, "Cannot find dict file: #{@file}" end dict = [] IO.readlines(@file).each do |line| line.strip! if line.length <= @chars && line =~ @allowed dict << line end end return dict end |