Module: Haddock::Password

Defined in:
lib/haddock.rb

Defined Under Namespace

Classes: LengthError, NoWordsError

Constant Summary collapse

MINIMUM =
8
MAXIMUM =
31
DEFAULT =
12
SYMBOLS =
'`~!@#$%^&*()-_=+[{]}\\|;:\'",<.>/?'
@@paths =
%w(/usr/share/dict/words /usr/share/words)

Class Method Summary collapse

Class Method Details

.diction=(path) ⇒ Object

Sets the dictionary. Uses “/usr/share/dict/words” or “/usr/share/words” otherwise.

Password.diction = File.expand_path(__FILE__) + "/my_words.txt"


46
47
48
49
50
51
52
# File 'lib/haddock.rb', line 46

def diction=(path)
  @@diction = IO.readlines path
rescue TypeError
  raise NoWordsError, "No words file found"
rescue Errno::ENOENT
  raise NoWordsError, "No words file at #{path.inspect}"
end

.generate(length = DEFAULT) ⇒ Object

Generates a more memorable password. Its one optional argument determines the length of the generated password, and cannot be less than 8 or greater than 31 characters (default: 12).

Password.generate     # => "bowl9&bracky"
Password.generate(30) # => "Phlebotomus2473?nonconditioned"
Password.generate(8)  # => "amy7@rax"

Raises:



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/haddock.rb', line 23

def generate(length = DEFAULT)
  unless defined? @@diction
    self.diction = @@paths.find { |path| File.exist? path }
  end

  raise LengthError, "Invalid length" unless length.is_a? Integer
  raise LengthError, "Password length is too short" if length < MINIMUM
  raise LengthError, "Password length is too long" if length > MAXIMUM

  words_limit = length * 0.75 # Ensure over-proportionate word lengths.

  begin
    words = %W(#{random_word} #{random_symbol}#{random_word})
    words_length = words.join.length
  end until words_length < length && words_length > words_limit

  words.join random_number(length - words_length)
end