Class: Chbs::Generator

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

Constant Summary collapse

DEFAULT_MIN_LENGTH =
4
DEFAULT_MAX_LENGTH =
10
DEFAULT_MIN_RANK =
1
DEFAULT_MAX_RANK =
10000
DEFAULT_NUM_WORDS =
4
DEFAULT_SEPARATOR =
'-'

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Generator

Returns a new instance of Generator.



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/chbs/generator.rb', line 10

def initialize(options={})
  min_length = options[:min_length] || DEFAULT_MIN_LENGTH
  max_length = options[:max_length] || DEFAULT_MAX_LENGTH
  min_rank = options[:min_rank] || DEFAULT_MIN_RANK
  max_rank = options[:max_rank] || DEFAULT_MAX_RANK
  @num_words = options[:num_words] || DEFAULT_NUM_WORDS
  @phrase_length = options[:phrase_length]
  @separator = options[:separator] || DEFAULT_SEPARATOR
  
  # Creating a temporary array is suboptimal, but it seems fast enough
  @words = []
  corpus = Chbs::load_corpus(options[:corpus])
  corpus.each do |word, wordstats|
    if (min_length..max_length).include?(wordstats['length']) &&
       (min_rank..max_rank).include?(wordstats['rank'])
      @words << word
    end
  end
end

Instance Attribute Details

#wordsObject (readonly)

Returns the value of attribute words.



9
10
11
# File 'lib/chbs/generator.rb', line 9

def words
  @words
end

Instance Method Details

#generateObject



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

def generate
  passwords = []
  if @phrase_length
    while passwords.join(@separator).length < @phrase_length
      passwords << @words[rand(@words.length-1)]
    end
    if passwords.join(@separator).length > @phrase_length
      passwords.pop
    end
  else
    @num_words.times do
      passwords << @words[rand(@words.length-1)]
    end
  end
  passwords.join(@separator)
end