Module: Haddock::Password

Defined in:
lib/haddock.rb

Defined Under Namespace

Classes: LengthError, NoWordsError

Constant Summary collapse

MINIMUM =

The minimum password legnth.

8
MAXIMUM =

The maximum password length.

31
DEFAULT =

The default password length.

12
PATHS =

Paths used to detect default words files.

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

Class Method Summary collapse

Class Method Details

.delimiters=(string) ⇒ Object

Sets the list of characters that can delimit words. Default:

`~!@#$%^&*()-_=+[{]}\|;:'",<.>/?


63
64
65
# File 'lib/haddock.rb', line 63

def delimiters=(string)
  @@delimiters = string
end

.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"


52
53
54
55
56
57
58
# File 'lib/haddock.rb', line 52

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:



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/haddock.rb', line 29

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_delimiter}#{random_word})
    words_length = words.join.length
  end until words_length < length && words_length > words_limit

  words.join random_number(length - words_length)
end