Class: JWTEasy::Result

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

Overview

Result object that represents a decoded token.

  • This is usually not instantiated directly, but rather by way of calling JWTEasy.encode.

Constant Summary collapse

CLAIM_KEYS =
[
  CLAIM_EXPIRATION_TIME,
  CLAIM_NOT_BEFORE_TIME
].freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(payload = nil, headers = nil) ⇒ Result

Initializes a new result instance.

Parameters:

  • payload (Object) (defaults to: nil)

    from decoding a token

  • headers (Hash) (defaults to: nil)

    from decoding a token



21
22
23
24
# File 'lib/jwt_easy/result.rb', line 21

def initialize(payload = nil, headers = nil)
  @payload = payload
  @headers = headers
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method, *arguments, &block) ⇒ Object



56
57
58
# File 'lib/jwt_easy/result.rb', line 56

def method_missing(method, *arguments, &block)
  data.is_a?(Hash) && data.key?(method.to_s) ? data[method.to_s] : super
end

Instance Attribute Details

#headersObject (readonly)

Returns the value of attribute headers.



14
15
16
# File 'lib/jwt_easy/result.rb', line 14

def headers
  @headers
end

#payloadObject (readonly)

Returns the value of attribute payload.



14
15
16
# File 'lib/jwt_easy/result.rb', line 14

def payload
  @payload
end

Instance Method Details

#claimSymbol

Infers the claim that was observed during decoding.

Returns:

  • (Symbol)

    short name for the identified claim



52
53
54
# File 'lib/jwt_easy/result.rb', line 52

def claim
  @claim ||= CLAIM_KEYS.find { |claim| payload&.key?(claim.to_s) }
end

#dataObject

Determines the encoded data from the payload structure.

  • If the payload is a hash that contains a claim key alongside other data

    attributes, only a hash with the data attributes will be returned.
    
  • If the payload is hash that contains data in a data attribute alongside any claim keys, the value of the data attribute is returned.

  • If the payload is anything but a hash, the payload is returned.

Returns:

  • (Object)

    the data encoded with the payload



37
38
39
40
41
42
43
44
45
46
47
# File 'lib/jwt_easy/result.rb', line 37

def data
  @data ||= if payload.is_a?(Hash)
              if claim && payload.key?('data')
                payload['data']
              else
                payload.except(*CLAIM_KEYS.map(&:to_s))
              end
            else
              payload
            end
end

#respond_to_missing?(method, _include_private = false) ⇒ Boolean

Returns:

  • (Boolean)


60
61
62
# File 'lib/jwt_easy/result.rb', line 60

def respond_to_missing?(method, _include_private = false)
  (data.is_a?(Hash) && data.key?(method.to_s)) || super
end