Class: OrganicHash

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

Constant Summary collapse

VERSION =
"1.0.1"
DATA_DIR =
File.expand_path(File.join(File.dirname(__FILE__), '..', 'data'))
NOUN =
File.read(File.join(DATA_DIR, "noun.dat")).split("\n")
ADJ =
File.read(File.join(DATA_DIR, "adj.dat")).split("\n")
ADV =
File.read(File.join(DATA_DIR, "adv.dat")).split("\n")

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(length = 3, delimiter = "-", hasher = Digest::SHA1, noun = NOUN, adj = ADJ, adv = ADV) ⇒ OrganicHash

Returns a new instance of OrganicHash.



12
13
14
15
16
17
18
19
# File 'lib/organic_hash.rb', line 12

def initialize(length = 3, delimiter = "-", hasher = Digest::SHA1, noun = NOUN, adj = ADJ, adv = ADV)
  @length = [1, [5, length].min].max
  @delimiter = delimiter
  @hasher = hasher
  @noun = noun
  @adj = adj
  @adv = adv
end

Class Method Details

.hash(str, array = false) ⇒ Object



38
39
40
# File 'lib/organic_hash.rb', line 38

def self.hash(str, array = false)
  OrganicHash.new.hash str, array
end

.rand(array = false) ⇒ Object



42
43
44
# File 'lib/organic_hash.rb', line 42

def self.rand(array = false)
  OrganicHash.new.rand array
end

Instance Method Details

#hash(str, array = false) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/organic_hash.rb', line 21

def hash(str, array = false)
  indexes = str2indexes str

  noun_idx = indexes.pop
  adjs, advs = indexes.partition.with_index { |_, i| i.even? }
  adjs = adjs.map { |i| @adj[i % @adj.length] }
  advs = advs.map { |i| @adv[i % @adv.length] }

  output = adjs.zip(advs).map(&:reverse).flatten.reject(&:nil?) + [@noun[noun_idx % @noun.length]]

  array ? output : output.join(@delimiter)
end

#rand(array = false) ⇒ Object



34
35
36
# File 'lib/organic_hash.rb', line 34

def rand(array = false)
 hash SecureRandom.hex, array
end