File: template.rb

package info (click to toggle)
ruby-dry-logger 1.1.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 156 kB
  • sloc: ruby: 802; makefile: 4
file content (92 lines) | stat: -rw-r--r-- 2,098 bytes parent folder | download | duplicates (2)
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
81
82
83
84
85
86
87
88
89
90
91
92
# frozen_string_literal: true

require "set"
require "dry/logger/constants"
require_relative "colors"

module Dry
  module Logger
    module Formatters
      # Basic string formatter.
      #
      # This formatter returns log entries in key=value format.
      #
      # @since 1.0.0
      # @api public
      class Template
        # @since 1.0.0
        # @api private
        TOKEN_REGEXP = /%<(\w*)>s/

        # @since 1.0.0
        # @api private
        MESSAGE_TOKEN = "%<message>s"

        # @since 1.0.0
        # @api private
        attr_reader :value

        # @since 1.0.0
        # @api private
        attr_reader :tokens

        # @since 1.0.0
        # @api private
        def self.[](value)
          cache.fetch(value) {
            cache[value] = (colorized?(value) ? Template::Colorized : Template).new(value)
          }
        end

        # @since 1.0.0
        # @api private
        private_class_method def self.colorized?(value)
          Colors::COLORS.keys.any? { |color| value.include?("<#{color}>") }
        end

        # @since 1.0.0
        # @api private
        private_class_method def self.cache
          @cache ||= {}
        end

        # @since 1.0.0
        # @api private
        class Colorized < Template
          # @since 1.0.0
          # @api private
          def initialize(value)
            super(Colors.evaluate(value))
          end
        end

        # @since 1.0.0
        # @api private
        def initialize(value)
          @value = value
          @tokens = value.scan(TOKEN_REGEXP).flatten(1).map(&:to_sym).to_set
        end

        # @since 1.0.0
        # @api private
        def %(tokens)
          output = value % tokens
          output.strip!
          output.split(NEW_LINE).map(&:rstrip).join(NEW_LINE)
        end

        # @since 1.0.0
        # @api private
        def colorize(color, input)
          "\e[#{Colors[color.to_sym]}m#{input}\e[0m"
        end

        # @since 1.0.0
        # @api private
        def include?(token)
          tokens.include?(token)
        end
      end
    end
  end
end