Module: Ashid::Encoder

Extended by:
Encoder
Included in:
Encoder
Defined in:
lib/ashid/encoder.rb

Constant Summary collapse

ALPHABET =
"0123456789abcdefghjkmnpqrstvwxyz".freeze

Instance Method Summary collapse

Instance Method Details

#decode(str) ⇒ Object



32
33
34
35
36
37
38
39
40
41
# File 'lib/ashid/encoder.rb', line 32

def decode(str)
  raise InvalidEncodingError, "empty string" if str.nil? || str.empty?

  str.each_char.reduce(0) do |acc, ch|
    v = DECODE_MAP[ch]
    raise InvalidEncodingError, "invalid character: #{ch.inspect}" if v.nil?

    acc * 32 + v
  end
end

#encode(n, padded: false) ⇒ Object

Raises:

  • (ArgumentError)


25
26
27
28
29
30
# File 'lib/ashid/encoder.rb', line 25

def encode(n, padded: false)
  raise ArgumentError, "must be non-negative" if n < 0

  str = encode_iterative(n)
  padded ? str.rjust(13, "0") : str
end

#secure_random(bits: 64) ⇒ Object

Raises:

  • (ArgumentError)


43
44
45
46
47
# File 'lib/ashid/encoder.rb', line 43

def secure_random(bits: 64)
  raise ArgumentError, "bits must be a positive multiple of 8" unless bits.is_a?(Integer) && bits.positive? && (bits % 8).zero?

  SecureRandom.bytes(bits / 8).bytes.reduce(0) { |acc, b| (acc << 8) | b }
end

#valid?(str) ⇒ Boolean

Returns:

  • (Boolean)


49
50
51
52
53
54
55
56
# File 'lib/ashid/encoder.rb', line 49

def valid?(str)
  return false unless str.is_a?(String)

  decode(str)
  true
rescue InvalidEncodingError
  false
end