Class: RuboCop::Cop::Style::IfUnlessModifier
Relationships & Source Files | |
Super Chains via Extension / Inclusion / Inheritance | |
Class Chain:
self,
::RuboCop::Cop::AutoCorrector ,
::RuboCop::Cop::Base ,
::RuboCop::ExcludeLimit ,
NodePattern::Macros,
RuboCop::AST::Sexp
|
|
Instance Chain:
self,
::RuboCop::Cop::CommentsHelp ,
::RuboCop::Cop::RangeHelp ,
::RuboCop::Cop::AllowedPattern ,
::RuboCop::Cop::StatementModifier ,
::RuboCop::Cop::LineLengthHelp ,
::RuboCop::Cop::Alignment ,
::RuboCop::Cop::Base ,
::RuboCop::Cop::AutocorrectLogic ,
::RuboCop::Cop::IgnoredNode ,
::RuboCop::Util ,
RuboCop::AST::Sexp
|
|
Inherits: |
RuboCop::Cop::Base
|
Defined in: | lib/rubocop/cop/style/if_unless_modifier.rb |
Overview
Checks for if
and unless
statements that would fit on one line if
written as modifier if
/unless
. The cop also checks for modifier
if
/unless
lines that exceed the maximum line length.
The maximum line length is configured in the Layout/LineLength
cop. The tab size is configured in the IndentationWidth
of the
Layout/IndentationStyle
cop.
One-line pattern matching is always allowed. To ensure that there are few cases
where the match variable is not used, and to prevent oversights. The variable x
becomes undefined and raises NameError
when the following example is changed to
the modifier form:
if [42] in [x]
x # {x} is undefined when using modifier form.
end
Note
|
It is allowed when defined? argument has an undefined value,
because using the modifier form causes the following incompatibility:
|
unless defined?(undefined_foo)
undefined_foo = 'default_value'
end
undefined_foo # => 'default_value'
= 'default_value' unless defined?( )
# => nil
Constant Summary
-
MSG_USE_MODIFIER =
# File 'lib/rubocop/cop/style/if_unless_modifier.rb', line 71'Favor modifier `%<keyword>s` usage when having a ' \ 'single-line body. Another good alternative is ' \ 'the usage of control flow `&&`/`||`.'
-
MSG_USE_NORMAL =
# File 'lib/rubocop/cop/style/if_unless_modifier.rb', line 74'Modifier form of `%<keyword>s` makes the line too long.'
::RuboCop::Cop::Base
- Inherited
EMPTY_OFFENSES, RESTRICT_ON_SEND
::RuboCop::Cop::Alignment
- Included
::RuboCop::Cop::RangeHelp
- Included
Class Attribute Summary
::RuboCop::Cop::AutoCorrector
- Extended
::RuboCop::Cop::Base
- Inherited
.gem_requirements, .lint?, | |
.support_autocorrect? | Returns if class supports autocorrect. |
.support_multiple_source? | Override if your cop should be called repeatedly for multiple investigations Between calls to |
Class Method Summary
::RuboCop::Cop::Base
- Inherited
.autocorrect_incompatible_with | List of cops that should not try to autocorrect at the same time as this cop. |
.badge | Naming. |
.callbacks_needed, .cop_name, .department, | |
.documentation_url | Returns a url to view this cops documentation online. |
.exclude_from_registry | Call for abstract Cop classes. |
.inherited, | |
.joining_forces | Override and return the Force class(es) you need to join. |
.match? | Returns true if the cop name or the cop namespace matches any of the given names. |
.new, | |
.requires_gem | Register a version requirement for the given gem name. |
.restrict_on_send |
::RuboCop::ExcludeLimit
- Extended
exclude_limit | Sets up a configuration option to have an exclude limit tracked. |
transform |
Instance Attribute Summary
::RuboCop::Cop::AllowedPattern
- Included
::RuboCop::Cop::LineLengthHelp
- Included
::RuboCop::Cop::Alignment
- Included
::RuboCop::Cop::Base
- Inherited
::RuboCop::Cop::AutocorrectLogic
- Included
Instance Method Summary
- #on_if(node)
- #allowed_patterns private
- #another_statement_on_same_line?(node) ⇒ Boolean private
- #autocorrect(corrector, node) private
- #comment_on_node_line(node) private
- #defined_argument_is_undefined?(if_node, defined_node) ⇒ Boolean private
- #defined_nodes(condition) private
- #extract_heredoc_from(last_argument) private
- #line_length_enabled_at_line?(line) ⇒ Boolean private
- #message(node) private
- #named_capture_in_condition?(node) ⇒ Boolean private
- #non_eligible_node?(node) ⇒ Boolean private
- #non_simple_if_unless?(node) ⇒ Boolean private
- #pattern_matching_nodes(condition) private
- #remove_comment(corrector, _node, comment) private
- #remove_heredoc(corrector, heredoc) private
- #replacement_for_modifier_form(corrector, node) private
- #to_modifier_form_with_move_comment(node, indentation, comment) private
- #to_normal_form(node, indentation) private
- #to_normal_form_with_heredoc(node, indentation, heredoc) private
- #too_long_due_to_comment_after_modifier?(node, comment) ⇒ Boolean private
- #too_long_due_to_modifier?(node) ⇒ Boolean private
- #too_long_line_based_on_allow_uri?(line) ⇒ Boolean private
- #too_long_line_based_on_config?(range, line) ⇒ Boolean private
- #too_long_line_based_on_ignore_cop_directives?(range, line) ⇒ Boolean private
- #too_long_single_line?(node) ⇒ Boolean private
::RuboCop::Cop::CommentsHelp
- Included
#comments_contain_disables?, #comments_in_range, #contains_comments?, #source_range_with_comment, #begin_pos_with_comment, #buffer, #end_position_for, | |
#find_end_line | Returns the end line of a node, which might be a comment and not part of the AST End line is considered either the line at which another node starts, or the line at which the parent node ends. |
#start_line_position |
::RuboCop::Cop::RangeHelp
- Included
#add_range, #column_offset_between, | |
#contents_range | A range containing only the contents of a literal with delimiters (e.g. |
#directions, | |
#effective_column | Returns the column attribute of the range, except if the range is on the first line and there’s a byte order mark at the beginning of that line, in which case 1 is subtracted from the column value. |
#final_pos, #move_pos, #move_pos_str, #range_between, #range_by_whole_lines, #range_with_comments, #range_with_comments_and_lines, #range_with_surrounding_comma, #range_with_surrounding_space, #source_range |
::RuboCop::Cop::AllowedPattern
- Included
#allowed_line?, #allowed_patterns, #cop_config_deprecated_methods_values, #cop_config_patterns_values, #matches_allowed_pattern? |
::RuboCop::Cop::StatementModifier
- Included
::RuboCop::Cop::LineLengthHelp
- Included
::RuboCop::Cop::Alignment
- Included
#check_alignment, #configured_indentation_width, #display_column, #each_bad_alignment, #end_of_line_comment, #indentation, #offset, #register_offense, #within? |
::RuboCop::Cop::Base
- Inherited
#add_global_offense | Adds an offense that has no particular location. |
#add_offense | Adds an offense on the specified range (or node with an expression) Unless that offense is disabled for this range, a corrector will be yielded to provide the cop the opportunity to autocorrect the offense. |
#begin_investigation | Called before any investigation. |
#callbacks_needed, | |
#cop_config | Configuration Helpers. |
#cop_name, #excluded_file?, | |
#external_dependency_checksum | This method should be overridden when a cop’s behavior depends on state that lives outside of these locations: |
#inspect, | |
#message | Gets called if no message is specified when calling |
#name | Alias for Base#cop_name. |
#offenses, | |
#on_investigation_end | Called after all on_… |
#on_new_investigation | Called before all on_… |
#on_other_file | Called instead of all on_… |
#parse | There should be very limited reasons for a Cop to do it’s own parsing. |
#parser_engine, | |
#ready | Called between investigations. |
#relevant_file?, | |
#target_gem_version | Returns a gems locked versions (i.e. |
#target_rails_version, #target_ruby_version, #annotate, #apply_correction, #attempt_correction, | |
#callback_argument | Reserved for Cop::Cop. |
#complete_investigation | Called to complete an investigation. |
#correct, #current_corrector, | |
#current_offense_locations | Reserved for Commissioner: |
#current_offenses, #currently_disabled_lines, #custom_severity, #default_severity, #disable_uncorrectable, #enabled_line?, #file_name_matches_any?, #find_message, #find_severity, #range_for_original, #range_from_node_or_range, | |
#reset_investigation | Actually private methods. |
#use_corrector |
::RuboCop::Cop::AutocorrectLogic
- Included
#disable_offense, #disable_offense_at_end_of_line, #disable_offense_before_and_after, #disable_offense_with_eol_or_surround_comment, #heredoc_range, #max_line_length, #multiline_ranges, #multiline_string?, | |
#range_by_lines | Expand the given range to include all of any lines it covers. |
#range_of_first_line, #range_overlaps_offense?, #string_continuation?, #surrounding_heredoc?, #surrounding_percent_array? |
::RuboCop::Cop::IgnoredNode
- Included
Constructor Details
This class inherits a constructor from RuboCop::Cop::Base
Class Method Details
.autocorrect_incompatible_with
[ GitHub ]# File 'lib/rubocop/cop/style/if_unless_modifier.rb', line 76
def self.autocorrect_incompatible_with [Style::SoleNestedConditional] end
Instance Method Details
#allowed_patterns (private)
[ GitHub ]# File 'lib/rubocop/cop/style/if_unless_modifier.rb', line 171
def allowed_patterns line_length_config = config.for_cop('Layout/LineLength') line_length_config['AllowedPatterns'] || line_length_config['IgnoredPatterns'] || [] end
#another_statement_on_same_line?(node) ⇒ Boolean
(private)
# File 'lib/rubocop/cop/style/if_unless_modifier.rb', line 231
def another_statement_on_same_line?(node) line_no = node.source_range.last_line # traverse the AST upwards until we find a 'begin' node # we want to look at the following child and see if it is on the # same line as this 'if' node while node && !node.begin_type? index = node.sibling_index node = node.parent end node && (sibling = node.children[index + 1]) && sibling.source_range.first_line == line_no end
#autocorrect(corrector, node) (private)
[ GitHub ]# File 'lib/rubocop/cop/style/if_unless_modifier.rb', line 132
def autocorrect(corrector, node) replacement = if node.modifier_form? replacement_for_modifier_form(corrector, node) else to_modifier_form(node) end corrector.replace(node, replacement) end
#comment_on_node_line(node) (private)
[ GitHub ]# File 'lib/rubocop/cop/style/if_unless_modifier.rb', line 285
def comment_on_node_line(node) processed_source.comments.find { |c| same_line?(c, node) } end
#defined_argument_is_undefined?(if_node, defined_node) ⇒ Boolean
(private)
# File 'lib/rubocop/cop/style/if_unless_modifier.rb', line 104
def defined_argument_is_undefined?(if_node, defined_node) defined_argument = defined_node.first_argument return false unless defined_argument.lvar_type? || defined_argument.send_type? if_node.left_siblings.none? do |sibling| sibling.respond_to?(:lvasgn_type?) && sibling.lvasgn_type? && sibling.name == defined_argument.node_parts[0] end end
#defined_nodes(condition) (private)
[ GitHub ]# File 'lib/rubocop/cop/style/if_unless_modifier.rb', line 96
def defined_nodes(condition) if condition.defined_type? [condition] else condition.each_descendant.select(&:defined_type?) end end
#extract_heredoc_from(last_argument) (private)
[ GitHub ]# File 'lib/rubocop/cop/style/if_unless_modifier.rb', line 272
def extract_heredoc_from(last_argument) heredoc_body = last_argument.loc.heredoc_body heredoc_end = last_argument.loc.heredoc_end [heredoc_body, heredoc_end] end
#line_length_enabled_at_line?(line) ⇒ Boolean
(private)
# File 'lib/rubocop/cop/style/if_unless_modifier.rb', line 215
def line_length_enabled_at_line?(line) processed_source.comment_config.cop_enabled_at_line?('Layout/LineLength', line) end
#message(node) (private)
[ GitHub ]# File 'lib/rubocop/cop/style/if_unless_modifier.rb', line 124
def (node) if single_line_as_modifier?(node) && !named_capture_in_condition?(node) MSG_USE_MODIFIER elsif too_long_due_to_modifier?(node) MSG_USE_NORMAL end end
#named_capture_in_condition?(node) ⇒ Boolean
(private)
# File 'lib/rubocop/cop/style/if_unless_modifier.rb', line 219
def named_capture_in_condition?(node) node.condition.match_with_lvasgn_type? end
#non_eligible_node?(node) ⇒ Boolean
(private)
# File 'lib/rubocop/cop/style/if_unless_modifier.rb', line 223
def non_eligible_node?(node) non_simple_if_unless?(node) || node.chained? || node.nested_conditional? || super end
#non_simple_if_unless?(node) ⇒ Boolean
(private)
# File 'lib/rubocop/cop/style/if_unless_modifier.rb', line 227
def non_simple_if_unless?(node) node.ternary? || node.elsif? || node.else? end
#on_if(node)
[ GitHub ]# File 'lib/rubocop/cop/style/if_unless_modifier.rb', line 80
def on_if(node) condition = node.condition return if defined_nodes(condition).any? { |n| defined_argument_is_undefined?(node, n) } || pattern_matching_nodes(condition).any? return unless (msg = (node)) add_offense(node.loc.keyword, message: format(msg, keyword: node.keyword)) do |corrector| next if part_of_ignored_node?(node) autocorrect(corrector, node) ignore_node(node) end end
#pattern_matching_nodes(condition) (private)
[ GitHub ]# File 'lib/rubocop/cop/style/if_unless_modifier.rb', line 114
def pattern_matching_nodes(condition) if condition.match_pattern_type? || condition.match_pattern_p_type? [condition] else condition.each_descendant.select do |node| node.match_pattern_type? || node.match_pattern_p_type? end end end
#remove_comment(corrector, _node, comment) (private)
[ GitHub ]# File 'lib/rubocop/cop/style/if_unless_modifier.rb', line 289
def remove_comment(corrector, _node, comment) corrector.remove(range_with_surrounding_space(range: comment.source_range, side: :left)) end
#remove_heredoc(corrector, heredoc) (private)
[ GitHub ]# File 'lib/rubocop/cop/style/if_unless_modifier.rb', line 279
def remove_heredoc(corrector, heredoc) heredoc.each do |range| corrector.remove(range_by_whole_lines(range, include_final_newline: true)) end end
#replacement_for_modifier_form(corrector, node) (private)
[ GitHub ]# File 'lib/rubocop/cop/style/if_unless_modifier.rb', line 141
def replacement_for_modifier_form(corrector, node) # rubocop:disable Metrics/AbcSize comment = comment_on_node_line(node) if comment && too_long_due_to_comment_after_modifier?(node, comment) remove_comment(corrector, node, comment) return to_modifier_form_with_move_comment(node, indent(node), comment) end last_argument = node.if_branch.last_argument if node.if_branch.send_type? if last_argument.respond_to?(:heredoc?) && last_argument.heredoc? heredoc = extract_heredoc_from(last_argument) remove_heredoc(corrector, heredoc) return to_normal_form_with_heredoc(node, indent(node), heredoc) end to_normal_form(node, indent(node)) end
#to_modifier_form_with_move_comment(node, indentation, comment) (private)
[ GitHub ]# File 'lib/rubocop/cop/style/if_unless_modifier.rb', line 265
def to_modifier_form_with_move_comment(node, indentation, comment) <<~RUBY.chomp #{comment.source} #{indentation}#{node.body.source} #{node.keyword} #{node.condition.source} RUBY end
#to_normal_form(node, indentation) (private)
[ GitHub ]# File 'lib/rubocop/cop/style/if_unless_modifier.rb', line 245
def to_normal_form(node, indentation) <<~RUBY.chomp #{node.keyword} #{node.condition.source} #{indentation} #{node.body.source} #{indentation}end RUBY end
#to_normal_form_with_heredoc(node, indentation, heredoc) (private)
[ GitHub ]# File 'lib/rubocop/cop/style/if_unless_modifier.rb', line 253
def to_normal_form_with_heredoc(node, indentation, heredoc) heredoc_body, heredoc_end = heredoc <<~RUBY.chomp #{node.keyword} #{node.condition.source} #{indentation} #{node.body.source} #{indentation} #{heredoc_body.source.chomp} #{indentation} #{heredoc_end.source.chomp} #{indentation}end RUBY end
#too_long_due_to_comment_after_modifier?(node, comment) ⇒ Boolean
(private)
# File 'lib/rubocop/cop/style/if_unless_modifier.rb', line 165
def too_long_due_to_comment_after_modifier?(node, comment) source_length = processed_source.lines[node.first_line - 1].length source_length >= max_line_length && source_length - comment.source_range.length <= max_line_length end
#too_long_due_to_modifier?(node) ⇒ Boolean
(private)
# File 'lib/rubocop/cop/style/if_unless_modifier.rb', line 160
def too_long_due_to_modifier?(node) node.modifier_form? && too_long_single_line?(node) && !another_statement_on_same_line?(node) end
#too_long_line_based_on_allow_uri?(line) ⇒ Boolean
(private)
# File 'lib/rubocop/cop/style/if_unless_modifier.rb', line 206
def too_long_line_based_on_allow_uri?(line) if allow_uri? uri_range = find_excessive_uri_range(line) return false if uri_range && allowed_uri_position?(line, uri_range) end true end
#too_long_line_based_on_config?(range, line) ⇒ Boolean
(private)
# File 'lib/rubocop/cop/style/if_unless_modifier.rb', line 189
def too_long_line_based_on_config?(range, line) return false if matches_allowed_pattern?(line) too_long = too_long_line_based_on_ignore_cop_directives?(range, line) return too_long unless too_long == :undetermined too_long_line_based_on_allow_uri?(line) end
#too_long_line_based_on_ignore_cop_directives?(range, line) ⇒ Boolean
(private)
# File 'lib/rubocop/cop/style/if_unless_modifier.rb', line 198
def too_long_line_based_on_ignore_cop_directives?(range, line) if ignore_cop_directives? && directive_on_source_line?(range.line - 1) return line_length_without_directive(line) > max_line_length end :undetermined end
#too_long_single_line?(node) ⇒ Boolean
(private)
# File 'lib/rubocop/cop/style/if_unless_modifier.rb', line 176
def too_long_single_line?(node) return false unless max_line_length range = node.source_range return false unless range.single_line? return false unless line_length_enabled_at_line?(range.first_line) line = range.source_line return false if line_length(line) <= max_line_length too_long_line_based_on_config?(range, line) end