Sha256: 046ae10b55333d6ba7cb03d151120144440d0956651fc5234850c5c9e8b48ccb

Contents?: true

Size: 1.17 KB

Versions: 1

Compression:

Stored size: 1.17 KB

Contents

# frozen_string_literal: true

module RuboCop
  module Cop
    module Performance
      # This cop identifies places where numeric argument to BigDecimal should be
      # converted to string. Initializing from String is faster
      # than from Numeric for BigDecimal.
      #
      # @example
      #
      #   # bad
      # BigDecimal(1, 2)
      # BigDecimal(1.2, 3, exception: true)
      #
      #   # good
      # BigDecimal('1', 2)
      # BigDecimal('1.2', 3, exception: true)
      #
      class BigDecimalWithNumericArgument < Cop
        MSG = 'Convert numeric argument to string before passing to `BigDecimal`.'

        def_node_matcher :big_decimal_with_numeric_argument?, <<~PATTERN
          (send nil? :BigDecimal $numeric_type? ...)
        PATTERN

        def on_send(node)
          big_decimal_with_numeric_argument?(node) do |numeric|
            add_offense(node, location: numeric.source_range)
          end
        end

        def autocorrect(node)
          big_decimal_with_numeric_argument?(node) do |numeric|
            lambda do |corrector|
              corrector.wrap(numeric, "'", "'")
            end
          end
        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
rubocop-performance-1.7.0 lib/rubocop/cop/performance/big_decimal_with_numeric_argument.rb