Sha256: a6d2463e126a1c312224237d0156ce714027e59f1cfe740ecf30127e91614883

Contents?: true

Size: 1 KB

Versions: 3

Compression:

Stored size: 1 KB

Contents

module RuboCop
  module Cop
    module Money
      # Prevents the use of `to_money` because it has inconsistent behaviour.
      # Use `Money.new` instead.
      #
      # @example
      #  # bad
      #  "2.000".to_money("USD")     #<Money value:2000.00 currency:USD>
      #
      #  # good
      #  Money.new("2.000", "USD")   #<Money value:2.00 currency:USD>
      class UnsafeToMoney < Cop
        MSG = '`to_money` has inconsistent behaviour. Use `Money.new` instead.'.freeze

        def on_send(node)
          return unless node.method?(:to_money)
          return if node.receiver.nil? || node.receiver.is_a?(AST::NumericNode)

          add_offense(node, location: :selector)
        end

        def autocorrect(node)
          lambda do |corrector|
            receiver = node.receiver.source
            args = node.arguments.map(&:source)
            args.prepend(receiver)
            corrector.replace(node.loc.expression, "Money.new(#{args.join(', ')})")
          end
        end
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
shopify-money-2.2.0 lib/rubocop/cop/money/unsafe_to_money.rb
shopify-money-2.0.0 lib/rubocop/cop/money/unsafe_to_money.rb
shopify-money-1.3.0 lib/rubocop/cop/money/unsafe_to_money.rb