File: set.rb

package info (click to toggle)
ruby-jwt 2.7.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 736 kB
  • sloc: ruby: 4,326; makefile: 4
file content (80 lines) | stat: -rw-r--r-- 1,826 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# frozen_string_literal: true

require 'forwardable'

module JWT
  module JWK
    class Set
      include Enumerable
      extend Forwardable

      attr_reader :keys

      def initialize(jwks = nil, options = {}) # rubocop:disable Metrics/CyclomaticComplexity
        jwks ||= {}

        @keys = case jwks
                when JWT::JWK::Set # Simple duplication
                  jwks.keys
                when JWT::JWK::KeyBase # Singleton
                  [jwks]
                when Hash
                  jwks = jwks.transform_keys(&:to_sym)
                  [*jwks[:keys]].map { |k| JWT::JWK.new(k, nil, options) }
                when Array
                  jwks.map { |k| JWT::JWK.new(k, nil, options) }
                else
                  raise ArgumentError, 'Can only create new JWKS from Hash, Array and JWK'
        end
      end

      def export(options = {})
        { keys: @keys.map { |k| k.export(options) } }
      end

      def_delegators :@keys, :each, :size, :delete, :dig

      def select!(&block)
        return @keys.select! unless block

        self if @keys.select!(&block)
      end

      def reject!(&block)
        return @keys.reject! unless block

        self if @keys.reject!(&block)
      end

      def uniq!(&block)
        self if @keys.uniq!(&block)
      end

      def merge(enum)
        @keys += JWT::JWK::Set.new(enum.to_a).keys
        self
      end

      def union(enum)
        dup.merge(enum)
      end

      def add(key)
        @keys << JWT::JWK.new(key)
        self
      end

      def ==(other)
        other.is_a?(JWT::JWK::Set) && keys.sort == other.keys.sort
      end

      alias eql? ==
      alias filter! select!
      alias length size
      # For symbolic manipulation
      alias | union
      alias + union
      alias << add
    end
  end
end