class RuboCop::Cop::Style::EmptyMethod

This cop checks for the formatting of empty method definitions. By default it enforces empty method definitions to go on a single line (compact style), but it can be configured to enforce the `end` to go on its own line (expanded style).

Note: A method definition is not considered empty if it contains

comments.

@example

# EnforcedStyle: compact (default)

# bad
def foo(bar)
end

def self.foo(bar)
end

# good
def foo(bar); end

def foo(bar)
  # baz
end

def self.foo(bar); end

@example

# EnforcedStyle: expanded

# bad
def foo(bar); end

def self.foo(bar); end

# good
def foo(bar)
end

def self.foo(bar)
end

Constants

MSG_COMPACT
MSG_EXPANDED

Public Instance Methods

on_def(node) click to toggle source
# File lib/rubocop/cop/style/empty_method.rb, line 56
def on_def(node)
  return if node.body || comment_lines?(node)
  return if correct_style?(node)

  add_offense(node)
end
Also aliased as: on_defs
on_defs(node)
Alias for: on_def

Private Instance Methods

autocorrect(node) click to toggle source
# File lib/rubocop/cop/style/empty_method.rb, line 66
def autocorrect(node)
  lambda do |corrector|
    corrector.replace(node.source_range, corrected(node))
  end
end
comment_lines?(node) click to toggle source
# File lib/rubocop/cop/style/empty_method.rb, line 96
def comment_lines?(node)
  processed_source[line_range(node)].any? { |line| comment_line?(line) }
end
compact?(node) click to toggle source
# File lib/rubocop/cop/style/empty_method.rb, line 100
def compact?(node)
  node.single_line?
end
compact_style?() click to toggle source
# File lib/rubocop/cop/style/empty_method.rb, line 108
def compact_style?
  style == :compact
end
correct_style?(node) click to toggle source
# File lib/rubocop/cop/style/empty_method.rb, line 76
def correct_style?(node)
  compact_style? && compact?(node) ||
    expanded_style? && expanded?(node)
end
corrected(node) click to toggle source
# File lib/rubocop/cop/style/empty_method.rb, line 81
def corrected(node)
  arguments = node.arguments? ? node.arguments.source : ''
  scope     = node.receiver ? "#{node.receiver.source}." : ''

  signature = [scope, node.method_name, arguments].join

  ["def #{signature}", 'end'].join(joint(node))
end
expanded?(node) click to toggle source
# File lib/rubocop/cop/style/empty_method.rb, line 104
def expanded?(node)
  node.multiline?
end
expanded_style?() click to toggle source
# File lib/rubocop/cop/style/empty_method.rb, line 112
def expanded_style?
  style == :expanded
end
joint(node) click to toggle source
# File lib/rubocop/cop/style/empty_method.rb, line 90
def joint(node)
  indent = ' ' * node.loc.column

  compact_style? ? '; ' : "\n#{indent}"
end
message(_node) click to toggle source
# File lib/rubocop/cop/style/empty_method.rb, line 72
def message(_node)
  compact_style? ? MSG_COMPACT : MSG_EXPANDED
end