Class: Hashids

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

Constant Summary collapse

VERSION =
"1.0.5"
MIN_ALPHABET_LENGTH =
16
SEP_DIV =
3.5
GUARD_DIV =
12.0
DEFAULT_SEPS =
"cfhistuCFHISTU"
DEFAULT_ALPHABET =
"abcdefghijklmnopqrstuvwxyz" +
"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
"1234567890"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(salt = "", min_hash_length = 0, alphabet = DEFAULT_ALPHABET) ⇒ Hashids

Returns a new instance of Hashids.



18
19
20
21
22
23
24
# File 'lib/hashids.rb', line 18

def initialize(salt = "", min_hash_length = 0, alphabet = DEFAULT_ALPHABET)
  @salt             = salt
  @min_hash_length  = min_hash_length
  @alphabet         = alphabet

  setup_alphabet
end

Instance Attribute Details

#alphabetObject (readonly)

Returns the value of attribute alphabet.



16
17
18
# File 'lib/hashids.rb', line 16

def alphabet
  @alphabet
end

#guardsObject (readonly)

Returns the value of attribute guards.



16
17
18
# File 'lib/hashids.rb', line 16

def guards
  @guards
end

#min_hash_lengthObject (readonly)

Returns the value of attribute min_hash_length.



16
17
18
# File 'lib/hashids.rb', line 16

def min_hash_length
  @min_hash_length
end

#saltObject (readonly)

Returns the value of attribute salt.



16
17
18
# File 'lib/hashids.rb', line 16

def salt
  @salt
end

#sepsObject (readonly)

Returns the value of attribute seps.



16
17
18
# File 'lib/hashids.rb', line 16

def seps
  @seps
end

Instance Method Details

#decode(hash) ⇒ Object



46
47
48
49
50
# File 'lib/hashids.rb', line 46

def decode(hash)
  return [] if hash.nil? || hash.empty?

  internal_decode(hash, @alphabet)
end

#decode_hex(hash) ⇒ Object



52
53
54
55
56
57
58
59
60
61
# File 'lib/hashids.rb', line 52

def decode_hex(hash)
  ret = ""
  numbers = decode(hash)

  numbers.length.times do |i|
    ret += numbers[i].to_s(16)[1 .. -1]
  end

  ret.upcase
end

#encode(*numbers) ⇒ Object



26
27
28
29
30
31
32
33
34
# File 'lib/hashids.rb', line 26

def encode(*numbers)
  numbers.flatten! if numbers.length == 1

  numbers.map! { |n| Integer(n) } # raises if conversion fails

  return '' if numbers.empty? || numbers.any? { |n| n < 0 }

  internal_encode(numbers)
end

#encode_hex(str) ⇒ Object



36
37
38
39
40
41
42
43
44
# File 'lib/hashids.rb', line 36

def encode_hex(str)
  return "" unless hex_string?(str)

  numbers = str.scan(/[\w\W]{1,12}/).map do |num|
    "1#{num}".to_i(16)
  end

  encode(numbers)
end