class RuboCop::Cop::Style::OrAssignment
This cop 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 47 def on_if(node) return unless unless_assignment?(node) add_offense(node) end
Private Instance Methods
autocorrect(node)
click to toggle source
# File lib/rubocop/cop/style/or_assignment.rb, line 63 def autocorrect(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 lambda do |corrector| corrector.replace(node.source_range, "#{variable} ||= #{default.source}") end end
take_variable_and_default_from_ternary(node)
click to toggle source
# File lib/rubocop/cop/style/or_assignment.rb, line 76 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 81 def take_variable_and_default_from_unless(node) variable, default = *node.if_branch [variable, default] end