class RuboCop::Cop::Style::NestedTernaryOperator
Checks for nested ternary op expressions.
@example
# bad a ? (b ? b1 : b2) : a2 # good if a b ? b1 : b2 else a2 end
Constants
- MSG
Public Instance Methods
on_if(node)
click to toggle source
# File lib/rubocop/cop/style/nested_ternary_operator.rb, line 25 def on_if(node) return unless node.ternary? node.each_descendant(:if).select(&:ternary?).each do |nested_ternary| add_offense(nested_ternary) do |corrector| next if part_of_ignored_node?(node) autocorrect(corrector, node) ignore_node(node) end end end
Private Instance Methods
autocorrect(corrector, if_node)
click to toggle source
# File lib/rubocop/cop/style/nested_ternary_operator.rb, line 40 def autocorrect(corrector, if_node) replace_loc_and_whitespace(corrector, if_node.loc.question, "\n") replace_loc_and_whitespace(corrector, if_node.loc.colon, "\nelse\n") corrector.replace(if_node.if_branch, remove_parentheses(if_node.if_branch.source)) corrector.wrap(if_node, 'if ', "\nend") end
remove_parentheses(source)
click to toggle source
# File lib/rubocop/cop/style/nested_ternary_operator.rb, line 47 def remove_parentheses(source) return source unless source.start_with?('(') source.delete_prefix('(').delete_suffix(')') end
replace_loc_and_whitespace(corrector, range, replacement)
click to toggle source
# File lib/rubocop/cop/style/nested_ternary_operator.rb, line 53 def replace_loc_and_whitespace(corrector, range, replacement) corrector.replace( range_with_surrounding_space(range: range, whitespace: true), replacement ) end