Sha256: faa7b80f9e4f5d7a4915d9c9b6870a76981975ba14c0a9da176f42ba48cab38e

Contents?: true

Size: 1.29 KB

Versions: 13

Compression:

Stored size: 1.29 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`.'
        RESTRICT_ON_SEND = %i[BigDecimal].freeze

        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

13 entries across 13 versions & 1 rubygems

Version Path
rubocop-performance-1.12.0 lib/rubocop/cop/performance/big_decimal_with_numeric_argument.rb
rubocop-performance-1.11.5 lib/rubocop/cop/performance/big_decimal_with_numeric_argument.rb
rubocop-performance-1.11.4 lib/rubocop/cop/performance/big_decimal_with_numeric_argument.rb
rubocop-performance-1.11.3 lib/rubocop/cop/performance/big_decimal_with_numeric_argument.rb
rubocop-performance-1.11.2 lib/rubocop/cop/performance/big_decimal_with_numeric_argument.rb
rubocop-performance-1.11.1 lib/rubocop/cop/performance/big_decimal_with_numeric_argument.rb
rubocop-performance-1.11.0 lib/rubocop/cop/performance/big_decimal_with_numeric_argument.rb
rubocop-performance-1.10.2 lib/rubocop/cop/performance/big_decimal_with_numeric_argument.rb
rubocop-performance-1.10.1 lib/rubocop/cop/performance/big_decimal_with_numeric_argument.rb
rubocop-performance-1.10.0 lib/rubocop/cop/performance/big_decimal_with_numeric_argument.rb
rubocop-performance-1.9.2 lib/rubocop/cop/performance/big_decimal_with_numeric_argument.rb
rubocop-performance-1.9.1 lib/rubocop/cop/performance/big_decimal_with_numeric_argument.rb
rubocop-performance-1.9.0 lib/rubocop/cop/performance/big_decimal_with_numeric_argument.rb