123456789_123456789_123456789_123456789_123456789_

Class: RuboCop::Cop::Style::RandomWithOffset

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/random_with_offset.rb

Overview

Checks for the use of randomly generated numbers, added/subtracted with integer literals, as well as those with Integer#succ and Integer#pred methods. Prefer using ranges instead, as it clearly states the intentions.

Examples:

# bad
rand(6) + 1
1 + rand(6)
rand(6) - 1
1 - rand(6)
rand(6).succ
rand(6).pred
Random.rand(6) + 1
Kernel.rand(6) + 1
rand(0..5) + 1

# good
rand(1..6)
rand(1...7)

Constant Summary

::RuboCop::Cop::Base - Inherited

EMPTY_OFFENSES, RESTRICT_ON_SEND

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 on_new_investigation and on_investigation_end, the result of processed_source will remain constant.

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

Instance Method Summary

::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 add_offense or add_global_offense Cops are discouraged to override this; instead pass your message directly.

#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

::RuboCop::Cop::IgnoredNode - Included

Constructor Details

This class inherits a constructor from RuboCop::Cop::Base

Instance Method Details

#autocorrect(corrector, node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/random_with_offset.rb', line 78

def autocorrect(corrector, node)
  if integer_op_rand?(node)
    corrector.replace(node, corrected_integer_op_rand(node))
  elsif rand_op_integer?(node)
    corrector.replace(node, corrected_rand_op_integer(node))
  elsif rand_modified?(node)
    corrector.replace(node, corrected_rand_modified(node))
  end
end

#boundaries_from_random_node(random_node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/random_with_offset.rb', line 135

def boundaries_from_random_node(random_node)
  case random_node.type
  when :int
    [0, to_int(random_node) - 1]
  when :irange
    [to_int(random_node.begin), to_int(random_node.end)]
  when :erange
    [to_int(random_node.begin), to_int(random_node.end) - 1]
  end
end

#corrected_integer_op_rand(node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/random_with_offset.rb', line 88

def corrected_integer_op_rand(node)
  random_call(node) do |prefix_node, random_node|
    prefix = prefix_from_prefix_node(prefix_node)
    left_int, right_int = boundaries_from_random_node(random_node)

    offset = to_int(node.receiver)

    if node.method?(:+)
      "#{prefix}(#{offset + left_int}..#{offset + right_int})"
    else
      "#{prefix}(#{offset - right_int}..#{offset - left_int})"
    end
  end
end

#corrected_rand_modified(node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/random_with_offset.rb', line 118

def corrected_rand_modified(node)
  random_call(node) do |prefix_node, random_node|
    prefix = prefix_from_prefix_node(prefix_node)
    left_int, right_int = boundaries_from_random_node(random_node)

    if %i[succ next].include?(node.method_name)
      "#{prefix}(#{left_int + 1}..#{right_int + 1})"
    elsif node.method?(:pred)
      "#{prefix}(#{left_int - 1}..#{right_int - 1})"
    end
  end
end

#corrected_rand_op_integer(node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/random_with_offset.rb', line 103

def corrected_rand_op_integer(node)
  random_call(node) do |prefix_node, random_node|
    prefix = prefix_from_prefix_node(prefix_node)
    left_int, right_int = boundaries_from_random_node(random_node)

    offset = to_int(node.first_argument)

    if node.method?(:+)
      "#{prefix}(#{left_int + offset}..#{right_int + offset})"
    else
      "#{prefix}(#{left_int - offset}..#{right_int - offset})"
    end
  end
end

#integer_op_rand?(node)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/random_with_offset.rb', line 33

def_node_matcher :integer_op_rand?, <<~PATTERN
  (send
    int {:+ :-}
    (send
      {nil? (const {nil? cbase} :Random) (const {nil? cbase} :Kernel)}
      :rand
      {int (irange int int) (erange int int)}))
PATTERN

#on_send(node)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/random_with_offset.rb', line 63

def on_send(node)
  return unless node.receiver
  return unless integer_op_rand?(node) || rand_op_integer?(node) || rand_modified?(node)

  add_offense(node) { |corrector| autocorrect(corrector, node) }
end

#prefix_from_prefix_node(node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/random_with_offset.rb', line 131

def prefix_from_prefix_node(node)
  [node&.source, 'rand'].compact.join('.')
end

#rand_modified?(node)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/random_with_offset.rb', line 54

def_node_matcher :rand_modified?, <<~PATTERN
  (send
    (send
      {nil? (const {nil? cbase} :Random) (const {nil? cbase} :Kernel)}
      :rand
      {int (irange int int) (erange int int)})
    {:succ :pred :next})
PATTERN

#rand_op_integer?(node)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/random_with_offset.rb', line 43

def_node_matcher :rand_op_integer?, <<~PATTERN
  (send
    (send
      {nil? (const {nil? cbase} :Random) (const {nil? cbase} :Kernel)}
      :rand
      {int (irange int int) (erange int int)})
    {:+ :-}
    int)
PATTERN

#random_call(node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/random_with_offset.rb', line 73

def_node_matcher :random_call, <<~PATTERN
  {(send (send $_ _ $_) ...)
   (send _ _ (send $_ _ $_))}
PATTERN

#to_int(node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/random_with_offset.rb', line 147

def_node_matcher :to_int, <<~PATTERN
  (int $_)
PATTERN