File: multiply_formatter.rb

package info (click to toggle)
ruby-lumberjack 2.0.4-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 956 kB
  • sloc: ruby: 7,957; makefile: 2
file content (35 lines) | stat: -rw-r--r-- 1,335 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
# frozen_string_literal: true

module Lumberjack
  class Formatter
    # This formatter can be used to multiply a numeric value by a specified multiplier and
    # optionally round to a specified number of decimal places.
    #
    # This is useful for unit conversions (e.g., converting seconds to milliseconds)
    # or scaling values for display purposes. Non-numeric values are passed through unchanged.
    class MultiplyFormatter
      FormatterRegistry.add(:multiply, self)

      # @param multiplier [Numeric] The multiplier to apply to the value.
      # @param decimals [Integer, nil] The number of decimal places to round the result to.
      #   If nil, no rounding is applied.
      def initialize(multiplier, decimals = nil)
        @multiplier = multiplier
        @decimals = decimals
      end

      # Multiply a numeric value by the configured multiplier and optionally round.
      #
      # @param value [Object] The value to format. Only numeric values are processed.
      # @return [Numeric, Object] The multiplied (and optionally rounded) value if numeric,
      #   otherwise returns the original value unchanged.
      def call(value)
        return value unless value.is_a?(Numeric)

        value *= @multiplier
        value = value.round(@decimals) if @decimals
        value
      end
    end
  end
end