Class: HumanHash::HumanHasher

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(opts = {}) ⇒ HumanHasher

Returns a new instance of HumanHasher.



12
13
14
15
16
17
# File 'lib/humanhash.rb', line 12

def initialize(opts={})
  @words = opts.fetch(:words, 4)
  @separator = opts.fetch(:separator, '-')
  @wordlist = opts.fetch(:wordlist, DEFAULT_WORDLIST)
  nil
end

Instance Attribute Details

#separatorObject

Returns the value of attribute separator.



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

def separator
  @separator
end

#wordlistObject

Returns the value of attribute wordlist.



10
11
12
# File 'lib/humanhash.rb', line 10

def wordlist
  @wordlist
end

#wordsObject

Returns the value of attribute words.



8
9
10
# File 'lib/humanhash.rb', line 8

def words
  @words
end

Instance Method Details

#compress(bytes, target) ⇒ Object



24
25
26
27
28
29
30
# File 'lib/humanhash.rb', line 24

def compress(bytes, target)
  len = bytes.size
  return bytes unless target < len

  segment_size = (len / target) + 1;
  bytes.each_slice(segment_size).map{|x| x.reduce{|s,b| s ^ b}}
end

#humanize(hexdigest) ⇒ Object



19
20
21
22
# File 'lib/humanhash.rb', line 19

def humanize(hexdigest)
  bytes = [hexdigest].pack("H*").bytes.to_a
  compress(bytes, words).map{|x| wordlist[x]}.join(separator)
end

#uuidObject



32
33
34
35
# File 'lib/humanhash.rb', line 32

def uuid
  uuid = SecureRandom.uuid.gsub('-', '')
  [ humanize(uuid), uuid ]
end