class RuboCop::Cop::Style::OrAssignment
Checks for potential usage of the `||=` operator.
@example
# bad name = name ? name : 'Bozhidar' # bad name = if name name else 'Bozhidar' end # bad unless name name = 'Bozhidar' end # bad name = 'Bozhidar' unless name # good - set name to 'Bozhidar', only if it's nil or false name ||= 'Bozhidar'
Constants
- MSG
Public Instance Methods
on_if(node)
click to toggle source
# File lib/rubocop/cop/style/or_assignment.rb, line 51 def on_if(node) return unless unless_assignment?(node) add_offense(node) { |corrector| autocorrect(corrector, node) } end
on_lvasgn(node)
click to toggle source
# File lib/rubocop/cop/style/or_assignment.rb, line 57 def on_lvasgn(node) return unless (else_branch = ternary_assignment?(node)) return if else_branch.if_type? add_offense(node) { |corrector| autocorrect(corrector, node) } end
Private Instance Methods
autocorrect(corrector, node)
click to toggle source
# File lib/rubocop/cop/style/or_assignment.rb, line 70 def autocorrect(corrector, node) if ternary_assignment?(node) variable, default = take_variable_and_default_from_ternary(node) else variable, default = take_variable_and_default_from_unless(node) end corrector.replace(node, "#{variable} ||= #{default.source}") end
take_variable_and_default_from_ternary(node)
click to toggle source
# File lib/rubocop/cop/style/or_assignment.rb, line 80 def take_variable_and_default_from_ternary(node) variable, if_statement = *node [variable, if_statement.else_branch] end
take_variable_and_default_from_unless(node)
click to toggle source
# File lib/rubocop/cop/style/or_assignment.rb, line 85 def take_variable_and_default_from_unless(node) if node.if_branch variable, default = *node.if_branch else variable, default = *node.else_branch end [variable, default] end