Class: Generator

Inherits:
Object
  • Object
show all
Defined in:
lib/spass.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

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', options={})
  @file = file
  @allowed = options[:allowed] || /^[a-z]+$/
  @chars = (options[:chars] || 10).to_i
  @dict = read_dict
end

Instance Attribute Details

#allowedObject (readonly)

Returns the value of attribute allowed.



3
4
5
# File 'lib/spass.rb', line 3

def allowed
  @allowed
end

#charsObject (readonly)

Returns the value of attribute chars.



3
4
5
# File 'lib/spass.rb', line 3

def chars
  @chars
end

#dictObject (readonly)

Returns the value of attribute dict.



3
4
5
# File 'lib/spass.rb', line 3

def dict
  @dict
end

#fileObject (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, options={})
  words = []
  num_words.times do
    word = random_word
    word += random_number.to_s if options[:digits]
    words << word
  end
  return words.join(' ')
end

#random_numberObject

Return a random number from 0 to 9



35
36
37
# File 'lib/spass.rb', line 35

def random_number
  rand(10)
end

#random_wordObject

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_dictObject

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