Class: RuboCop::Cop::Money::UnsafeToMoney

Inherits:
RuboCop::Cop show all
Defined in:
lib/rubocop/cop/money/unsafe_to_money.rb

Overview

Prevents the use of ‘to_money` because it has inconsistent behaviour. Use `Money.new` instead.

Examples:

# bad
"2.000".to_money("USD")     #<Money value:2000.00 currency:USD>

# good
Money.new("2.000", "USD")   #<Money value:2.00 currency:USD>

Constant Summary collapse

MSG =
'`to_money` has inconsistent behaviour. Use `Money.new` instead.'.freeze

Instance Method Summary collapse

Instance Method Details

#autocorrect(node) ⇒ Object



24
25
26
27
28
29
30
31
# File 'lib/rubocop/cop/money/unsafe_to_money.rb', line 24

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

#on_send(node) ⇒ Object



17
18
19
20
21
22
# File 'lib/rubocop/cop/money/unsafe_to_money.rb', line 17

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