Class: Ducalis::PreferableMethods

Inherits:
RuboCop::Cop::Cop
  • Object
show all
Defined in:
lib/ducalis/cops/preferable_methods.rb

Constant Summary collapse

OFFENSE =
<<-MESSAGE.gsub(/^ +\|\s/, '').strip
  | Prefer to use %<alternative>s method instead of %<original>s because of %<reason>s.
MESSAGE
ALWAYS_TRUE =
->(_who, _what, _args) { true }
VALIDATE_CHECK =
lambda do |_who, _what, args|
  (args.first && args.first.source) =~ /validate/
end
DESCRIPTION =
{
  # Method => [
  #   Alternative,
  #   Reason,
  #   Callable condition
  # ]
  toggle!: [
    '`toggle.save`',
    'it is not invoking validations',
    ALWAYS_TRUE
  ],
  save: [
    '`save`',
    'it is not invoking validations',
    VALIDATE_CHECK
  ],
  delete: [
    '`destroy`',
    'it is not invoking callbacks',
    ComplexCases::SmartDeleteCheck
  ],
  delete_all: [
    '`destroy_all`',
    'it is not invoking callbacks',
    ALWAYS_TRUE
  ],
  update_attribute: [
    '`update` (`update_attributes` for Rails versions < 4)',
    'it is not invoking validations',
    ALWAYS_TRUE
  ],
  update_column: [
    '`update` (`update_attributes` for Rails versions < 4)',
    'it is not invoking callbacks',
    ALWAYS_TRUE
  ],
  update_columns: [
    '`update` (`update_attributes` for Rails versions < 4)',
    'it is not invoking validations, callbacks and updated_at',
    ALWAYS_TRUE
  ]
}.freeze
DETAILS =
"Dangerous methods are:
#{DESCRIPTION.keys.map { |name| "`#{name}`" }.join(', ')}.".freeze

Instance Method Summary collapse

Instance Method Details

#on_send(node) ⇒ Object



64
65
66
67
68
69
70
71
72
73
74
# File 'lib/ducalis/cops/preferable_methods.rb', line 64

def on_send(node)
  who, what, *args = *node
  return unless DESCRIPTION.key?(what)

  alternative, reason, condition = DESCRIPTION.fetch(what)
  return unless condition.call(who, what, args)

  add_offense(node, :expression, format(OFFENSE, original: what,
                                                 alternative: alternative,
                                                 reason: reason))
end