Module: ReadableToken

Defined in:
lib/readable-token.rb,
lib/readable-token/version.rb

Overview

A tiny Ruby library for generating human readable “tokens”.

Defined Under Namespace

Classes: TestCase

Constant Summary collapse

Version =
'0.1.1'

Class Method Summary collapse

Class Method Details

.generate(opts = {}) ⇒ Object

Generate a new token.



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/readable-token.rb', line 17

def self.generate(opts = {})
  # set default options and merge with user provided
  options = {
    min: 8,
    max: nil
  }.merge(opts)

  segments = []

  # add number
  segments << rand(1..9).to_s

  # count number of loops so were not spinning our wheels if we can't meet
  # the criteria requested by the user.
  looped = 0
  while current_length_of(segments) < options[:min]
    new_word = ''
    remove_blanks!(segments)

    looped += 1
    break if looped > 20

    current_length = current_length_of(segments)
    if options[:max] && options[:max] > 0
      remaining = options[:max] - current_length
      new_word = filter_by_length(words, remaining - 1).sample
    else
      new_word = words.sample
    end

    new_length = current_length_of(segments + [new_word])
    next if options[:max] && options[:max] > 0 && new_length > options[:max]

    segments << new_word
  end
  remove_blanks!(segments)

  # join it all together to give us a token
  segments.reverse.join('-')
end

.wordsObject

Access to current list of words



7
8
9
# File 'lib/readable-token.rb', line 7

def self.words
  @@words ||= %w{dream season applause music venue talk top spoon fork tea coffee soup eat drink chat social happy doughnut beans bistro cafe lunch java ruby penguin lion leopard cake tiger crab fish moo milk owl roast aroma balance barista blend body decaf espresso flavor mocha latte organic friend}
end

.words=(vals) ⇒ Object

Set list of words to the given array



12
13
14
# File 'lib/readable-token.rb', line 12

def self.words=(vals)
  @@words = vals
end