Sha256: ec440007a9afc553056641b0c45ad468a2ede9ca93592eb25e6c61ab34fa2595

Contents?: true

Size: 1.24 KB

Versions: 2

Compression:

Stored size: 1.24 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 < Base
        extend AutoCorrector

        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)
          return unless (numeric = big_decimal_with_numeric_argument?(node))
          return if numeric.float_type? && specifies_precision?(node)

          add_offense(numeric.source_range) do |corrector|
            corrector.wrap(numeric, "'", "'")
          end
        end

        private

        def specifies_precision?(node)
          node.arguments.size > 1 && !node.arguments[1].hash_type?
        end
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
rubocop-performance-1.8.1 lib/rubocop/cop/performance/big_decimal_with_numeric_argument.rb
rubocop-performance-1.8.0 lib/rubocop/cop/performance/big_decimal_with_numeric_argument.rb