File: normalized_cmd_name.rb

package info (click to toggle)
ruby-redis-cluster-client 0.10.0-1.1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 208 kB
  • sloc: ruby: 2,214; makefile: 4
file content (69 lines) | stat: -rw-r--r-- 1,445 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
# frozen_string_literal: true

require 'singleton'

class RedisClient
  class Cluster
    class NormalizedCmdName
      include Singleton

      EMPTY_STRING = ''

      def initialize
        @cache = {}
        @mutex = Mutex.new
      end

      def get_by_command(command)
        get(command, index: 0)
      end

      def get_by_subcommand(command)
        get(command, index: 1)
      end

      def get_by_name(name)
        get(name, index: 0)
      end

      def clear
        @mutex.synchronize { @cache.clear }
        true
      end

      private

      def get(command, index:)
        name = extract_name(command, index: index)
        return EMPTY_STRING if name.nil? || name.empty?

        normalize(name)
      end

      def extract_name(command, index:)
        case command
        when String, Symbol then index.zero? ? command : nil
        when Array then extract_name_from_array(command, index: index)
        end
      end

      def extract_name_from_array(command, index:)
        return if command.size - 1 < index

        case e = command[index]
        when String, Symbol then e
        when Array then e[index]
        end
      end

      def normalize(name)
        return @cache[name] || name.to_s.downcase if @cache.key?(name)
        return name.to_s.downcase if @mutex.locked?

        str = name.to_s.downcase
        @mutex.synchronize { @cache[name] = str }
        str
      end
    end
  end
end