Module: EncodedToken::Decoder

Included in:
EncodedToken
Defined in:
lib/encoded_token/decoder.rb

Overview

:nodoc:

Instance Method Summary collapse

Instance Method Details

#decode(id) ⇒ Object

Decode a previously encoded token to return the original ID

args:
  • token [String]

returns:
  • a String with the original ID

on error:
  • returns nil

examples:

EncodedToken.decode("KY3bnaRGmyy6yJS3imWr1dcWtzDYvZjpIAYyCUo5PEKPFvQgtTTed")
#=> "12345"

EncodedToken.decode("3gDwO7r4UJYeBYDBLU94MqjZQm0SToSE29ACDNcw0xf4QusZKxQHJ")
#=> "12345"

EncodedToken.decode("pAi1SmpKgFAchh76EoLbYLeXVQmLwmMlH2v1zDVeufioKGr0709Qw")
#=> "4ef2091f-023b-4af6-9e9f-f46465f897ba"

EncodedToken.decode("abcdefghijklmnopqrstuvwxyz")
#=> nil

EncodedToken.decode(:test)
#=> nil


90
91
92
93
94
# File 'lib/encoded_token/decoder.rb', line 90

def decode(id)
  decode!(id)
rescue
  nil
end

#decode!(token) ⇒ Object

Decode a previously encoded token to return the original ID

args:
  • token [String]

returns:
  • a String with the original ID

on error:
  • an invalid String token returns nil

  • otherwise an exception will be raised

examples:

EncodedToken.decode!("KY3bnaRGmyy6yJS3imWr1dcWtzDYvZjpIAYyCUo5PEKPFvQgtTTed")
#=> "12345"

EncodedToken.decode!("3gDwO7r4UJYeBYDBLU94MqjZQm0SToSE29ACDNcw0xf4QusZKxQHJ")
#=> "12345"

EncodedToken.decode!("pAi1SmpKgFAchh76EoLbYLeXVQmLwmMlH2v1zDVeufioKGr0709Qw")
#=> "468a5eeb-0cda-4c99-8dba-6a96c33003e0"

EncodedToken.decode!("abcdefghijklmnopqrstuvwxyz")
#=> nil

EncodedToken.decode!(:test)
#=> Token is not a string. (RuntimeError)


45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/encoded_token/decoder.rb', line 45

def decode!(token)
  assert_valid_seed!

  token = sanitize_token(token)
  id    = parse_token(token)

  # is it a UUID or numeric ID
  if valid_integer?(id) || valid_uuid_format?(id)
    return id
  else
    return nil
  end
end