Class: RuboCop::Cop::Style::GuardClause
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:
|
|
Inherits: |
RuboCop::Cop::Base
|
Defined in: | lib/rubocop/cop/style/guard_clause.rb |
Overview
Use a guard clause instead of wrapping the code inside a conditional expression
A condition with an elsif
or else
branch is allowed unless
one of return
, break
, next
, raise
, or fail
is used
in the body of the conditional expression.
Note
|
Autocorrect works in most cases except with if-else statements
that contain logical operators such as foo || raise('exception')
|
Constant Summary
-
MSG =
# File 'lib/rubocop/cop/style/guard_clause.rb', line 120'Use a guard clause (`%<example>s`) instead of wrapping the ' \ 'code inside a conditional expression.'
::RuboCop::Cop::Base
- Inherited
EMPTY_OFFENSES, RESTRICT_ON_SEND
::RuboCop::Cop::RangeHelp
- Included
::RuboCop::Cop::Alignment
- 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
- #allowed_consecutive_conditionals? ⇒ Boolean readonly private
::RuboCop::Cop::LineLengthHelp
- Included
::RuboCop::Cop::Alignment
- Included
::RuboCop::Cop::Base
- Inherited
::RuboCop::Cop::AutocorrectLogic
- Included
Instance Method Summary
- #on_block(node) (also: #on_numblock)
- #on_def(node) (also: #on_defs)
-
#on_defs(node)
Alias for #on_def.
- #on_if(node)
-
#on_numblock(node)
Alias for #on_block.
- #accepted_form?(node, ending: false) ⇒ Boolean private
- #accepted_if?(node, ending) ⇒ Boolean private
- #and_or_guard_clause?(guard_clause) ⇒ Boolean private
- #assigned_lvar_used_in_if_branch?(node) ⇒ Boolean private
-
#autocorrect(corrector, node, condition, replacement, guard)
private
Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity.
- #autocorrect_heredoc_argument(corrector, node, heredoc_branch, leave_branch, guard) private
- #check_ending_body(body) private
- #check_ending_if(node) private
- #consecutive_conditionals?(parent, node) ⇒ Boolean private
- #guard_clause_source(guard_clause) private
-
#heredoc?(argument) ⇒ Boolean
private
Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity.
- #range_of_branch_to_remove(node, guard) private
- #register_offense(node, scope_exiting_keyword, conditional_keyword, guard = nil) private
- #remove_whole_lines(corrector, range) private
- #too_long_for_single_line?(node, example) ⇒ Boolean private
- #trivial?(node) ⇒ Boolean private
::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::MinBodyLength
- Included
::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::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_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, #max_line_length, | |
#range_by_lines | Expand the given range to include all of any lines it covers. |
#range_of_first_line, #range_overlaps_offense?, #string_continuation, #string_continuation?, #surrounding_heredoc, #surrounding_percent_array |
::RuboCop::Cop::IgnoredNode
- Included
Constructor Details
This class inherits a constructor from RuboCop::Cop::Base
Instance Attribute Details
#allowed_consecutive_conditionals? ⇒ Boolean
(readonly, private)
[ GitHub ]
# File 'lib/rubocop/cop/style/guard_clause.rb', line 312
def allowed_consecutive_conditionals? cop_config.fetch('AllowConsecutiveConditionals', false) end
Instance Method Details
#accepted_form?(node, ending: false) ⇒ Boolean
(private)
# File 'lib/rubocop/cop/style/guard_clause.rb', line 275
def accepted_form?(node, ending: false) accepted_if?(node, ending) || node.condition.multiline? || node.parent&.assignment? end
#accepted_if?(node, ending) ⇒ Boolean
(private)
# File 'lib/rubocop/cop/style/guard_clause.rb', line 285
def accepted_if?(node, ending) return true if node.modifier_form? || node.ternary? || node.elsif_conditional? || assigned_lvar_used_in_if_branch?(node) if ending node.else? else !node.else? || node.elsif? end end
#and_or_guard_clause?(guard_clause) ⇒ Boolean
(private)
# File 'lib/rubocop/cop/style/guard_clause.rb', line 265
def and_or_guard_clause?(guard_clause) parent = guard_clause.parent parent.operator_keyword? end
#assigned_lvar_used_in_if_branch?(node) ⇒ Boolean
(private)
# File 'lib/rubocop/cop/style/guard_clause.rb', line 296
def assigned_lvar_used_in_if_branch?(node) return false unless (if_branch = node.if_branch) assigned_lvars_in_condition = node.condition.each_descendant(:lvasgn).map do |lvasgn| lvar_name, = *lvasgn lvar_name.to_s end used_lvars_in_branch = if_branch.each_descendant(:lvar).map(&:source) || [] (assigned_lvars_in_condition & used_lvars_in_branch).any? end
#autocorrect(corrector, node, condition, replacement, guard) (private)
Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity
# File 'lib/rubocop/cop/style/guard_clause.rb', line 210
def autocorrect(corrector, node, condition, replacement, guard) corrector.replace(node.loc.keyword.join(condition.source_range), replacement) if_branch = node.if_branch else_branch = node.else_branch corrector.replace(node.loc.begin, "\n") if node.loc.begin&.is?('then') if if_branch&.send_type? && heredoc?(if_branch.last_argument) autocorrect_heredoc_argument(corrector, node, if_branch, else_branch, guard) elsif else_branch&.send_type? && heredoc?(else_branch.last_argument) autocorrect_heredoc_argument(corrector, node, else_branch, if_branch, guard) else corrector.remove(node.loc.end) return unless node.else? corrector.remove(node.loc.else) corrector.remove(range_of_branch_to_remove(node, guard)) end end
#autocorrect_heredoc_argument(corrector, node, heredoc_branch, leave_branch, guard) (private)
[ GitHub ]# File 'lib/rubocop/cop/style/guard_clause.rb', line 236
def autocorrect_heredoc_argument(corrector, node, heredoc_branch, leave_branch, guard) remove_whole_lines(corrector, node.loc.end) return unless node.else? remove_whole_lines(corrector, leave_branch.source_range) remove_whole_lines(corrector, node.loc.else) remove_whole_lines(corrector, range_of_branch_to_remove(node, guard)) corrector.insert_after( heredoc_branch.last_argument.loc.heredoc_end, "\n#{leave_branch.source}" ) end
#check_ending_body(body) (private)
[ GitHub ]# File 'lib/rubocop/cop/style/guard_clause.rb', line 159
def check_ending_body(body) return if body.nil? if body.if_type? check_ending_if(body) elsif body.begin_type? final_expression = body.children.last check_ending_if(final_expression) if final_expression&.if_type? end end
#check_ending_if(node) (private)
[ GitHub ]# File 'lib/rubocop/cop/style/guard_clause.rb', line 170
def check_ending_if(node) return if accepted_form?(node, ending: true) || !min_body_length?(node) return if allowed_consecutive_conditionals? && consecutive_conditionals?(node.parent, node) register_offense(node, 'return', node.inverse_keyword) check_ending_body(node.if_branch) end
#consecutive_conditionals?(parent, node) ⇒ Boolean
(private)
# File 'lib/rubocop/cop/style/guard_clause.rb', line 180
def consecutive_conditionals?(parent, node) parent.each_child_node.inject(false) do |if_type, child| break if_type if node == child child.if_type? end end
#guard_clause_source(guard_clause) (private)
[ GitHub ]# File 'lib/rubocop/cop/style/guard_clause.rb', line 257
def guard_clause_source(guard_clause) if and_or_guard_clause?(guard_clause) guard_clause.parent.source else guard_clause.source end end
#heredoc?(argument) ⇒ Boolean
(private)
Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity
# File 'lib/rubocop/cop/style/guard_clause.rb', line 232
def heredoc?(argument) argument.respond_to?(:heredoc?) && argument.heredoc? end
#on_block(node) Also known as: #on_numblock
[ GitHub ]# File 'lib/rubocop/cop/style/guard_clause.rb', line 132
def on_block(node) return unless node.method?(:define_method) || node.method?(:define_singleton_method) on_def(node) end
#on_def(node) Also known as: #on_defs
[ GitHub ]# File 'lib/rubocop/cop/style/guard_clause.rb', line 123
def on_def(node) body = node.body return unless body check_ending_body(body) end
#on_defs(node)
Alias for #on_def.
# File 'lib/rubocop/cop/style/guard_clause.rb', line 130
alias on_defs on_def
#on_if(node)
[ GitHub ]# File 'lib/rubocop/cop/style/guard_clause.rb', line 139
def on_if(node) return if accepted_form?(node) if (guard_clause = node.if_branch&.guard_clause?) kw = node.loc.keyword.source guard = :if elsif (guard_clause = node.else_branch&.guard_clause?) kw = node.inverse_keyword guard = :else else return end guard = nil if and_or_guard_clause?(guard_clause) register_offense(node, guard_clause_source(guard_clause), kw, guard) end
#on_numblock(node)
Alias for #on_block.
# File 'lib/rubocop/cop/style/guard_clause.rb', line 137
alias on_numblock on_block
#range_of_branch_to_remove(node, guard) (private)
[ GitHub ]# File 'lib/rubocop/cop/style/guard_clause.rb', line 248
def range_of_branch_to_remove(node, guard) branch = case guard when :if then node.if_branch when :else then node.else_branch end branch.source_range end
#register_offense(node, scope_exiting_keyword, conditional_keyword, guard = nil) (private)
[ GitHub ]# File 'lib/rubocop/cop/style/guard_clause.rb', line 188
def register_offense(node, scope_exiting_keyword, conditional_keyword, guard = nil) condition, = node.node_parts example = [scope_exiting_keyword, conditional_keyword, condition.source].join(' ') if too_long_for_single_line?(node, example) return if trivial?(node) example = "#{conditional_keyword} #{condition.source}; #{scope_exiting_keyword}; end" replacement = <<~RUBY.chomp #{conditional_keyword} #{condition.source} #{scope_exiting_keyword} end RUBY end add_offense(node.loc.keyword, message: format(MSG, example: example)) do |corrector| next if node.else? && guard.nil? autocorrect(corrector, node, condition, replacement || example, guard) end end
#remove_whole_lines(corrector, range) (private)
[ GitHub ]# File 'lib/rubocop/cop/style/guard_clause.rb', line 308
def remove_whole_lines(corrector, range) corrector.remove(range_by_whole_lines(range, include_final_newline: true)) end
#too_long_for_single_line?(node, example) ⇒ Boolean
(private)
# File 'lib/rubocop/cop/style/guard_clause.rb', line 270
def too_long_for_single_line?(node, example) max = max_line_length max && node.source_range.column + example.length > max end
#trivial?(node) ⇒ Boolean
(private)
# File 'lib/rubocop/cop/style/guard_clause.rb', line 279
def trivial?(node) return false unless node.if_branch node.branches.one? && !node.if_branch.if_type? && !node.if_branch.begin_type? end