class RuboCop::Cop::Style::IfWithSemicolon
Checks for uses of semicolon in if statements.
@example
# bad result = if some_condition; something else another_thing end # good result = some_condition ? something : another_thing
Constants
- MSG_IF_ELSE
- MSG_TERNARY
Public Instance Methods
on_normal_if_unless(node)
click to toggle source
# File lib/rubocop/cop/style/if_with_semicolon.rb, line 23 def on_normal_if_unless(node) return unless node.else_branch return if node.parent&.if_type? beginning = node.loc.begin return unless beginning&.is?(';') message = node.else_branch.if_type? ? MSG_IF_ELSE : MSG_TERNARY add_offense(node, message: format(message, expr: node.condition.source)) do |corrector| corrector.replace(node, autocorrect(node)) end end
Private Instance Methods
autocorrect(node)
click to toggle source
# File lib/rubocop/cop/style/if_with_semicolon.rb, line 39 def autocorrect(node) return correct_elsif(node) if node.else_branch.if_type? else_code = node.else_branch ? node.else_branch.source : 'nil' "#{node.condition.source} ? #{node.if_branch.source} : #{else_code}" end
build_else_branch(second_condition)
click to toggle source
# File lib/rubocop/cop/style/if_with_semicolon.rb, line 56 def build_else_branch(second_condition) result = <<~RUBY elsif #{second_condition.condition.source} #{second_condition.if_branch.source} RUBY if second_condition.else_branch result += if second_condition.else_branch.if_type? build_else_branch(second_condition.else_branch) else <<~RUBY else #{second_condition.else_branch.source} RUBY end end result end
correct_elsif(node)
click to toggle source
# File lib/rubocop/cop/style/if_with_semicolon.rb, line 47 def correct_elsif(node) <<~RUBY.chop if #{node.condition.source} #{node.if_branch.source} #{build_else_branch(node.else_branch).chop} end RUBY end