Class: RuboCop::Cop::Lint::NumberConversion
| 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/lint/number_conversion.rb |
Overview
Warns against the usage of unsafe number conversions. Unsafe number conversion can cause an unexpected error if auto type conversion fails. The cop prefers parsing with a number class instead.
Conversion with Integer, Float, etc. will raise an ArgumentError
if given input that is not numeric (eg. an empty string), whereas
to_i, etc. will try to convert regardless of input (''.to_i ⇒ 0).
As such, this cop is disabled by default because it’s not necessarily
always correct to raise if a value is not numeric.
|
Note
|
Some values cannot be converted properly using one of the Kernel
methods (for instance, Time and DateTime values are allowed by this
cop by default). Similarly, Rails' duration methods do not work well
with Integer() and can be allowed with ::RuboCop::Cop::AllowedMethods. By default,
there are no allowed methods.
|
Constant Summary
-
CONVERSION_METHODS =
# File 'lib/rubocop/cop/lint/number_conversion.rb', line 88%i[Integer Float Complex Rational to_i to_f to_c to_r].freeze
-
CONVERSION_METHOD_CLASS_MAPPING =
# File 'lib/rubocop/cop/lint/number_conversion.rb', line 78{ to_i: "#{Integer.name}(%<number_object>s, 10)", to_f: "#{Float.name}(%<number_object>s)", to_c: "#{Complex.name}(%<number_object>s)", to_r: "#{Rational.name}(%<number_object>s)" }.freeze -
METHODS =
# File 'lib/rubocop/cop/lint/number_conversion.rb', line 89CONVERSION_METHOD_CLASS_MAPPING.keys.map(&:inspect).join(' ')
-
MSG =
# File 'lib/rubocop/cop/lint/number_conversion.rb', line 84'Replace unsafe number conversion with number ' \ 'class parsing, instead of using ' \ '`%<current>s`, use stricter ' \ '`%<corrected_method>s`.'
::RuboCop::Cop::Base - Inherited
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 | Reserved for Commissioner. |
::RuboCop::ExcludeLimit - Extended
| exclude_limit | Sets up a configuration option to have an exclude limit tracked. |
| transform | |
Instance Attribute Summary
::RuboCop::Cop::AllowedMethods - Included
::RuboCop::Cop::Base - Inherited
| #active_support_extensions_enabled?, #always_autocorrect?, #config, #config_to_allow_offenses, #config_to_allow_offenses=, #contextual_autocorrect?, #disabled_autocorrect?, | |
| #preview? | Whether the user opted in to unstable behavior, with |
| #processed_source, #project_index, #string_literals_frozen_by_default?, #target_satisfies_all_gem_version_requirements? | |
::RuboCop::Cop::AutocorrectLogic - Included
| #autocorrect?, #autocorrect_enabled?, #autocorrect_requested?, #autocorrect_with_disable_uncorrectable?, #correctable?, #disable_uncorrectable?, #safe_autocorrect?, | |
| #skipped_unsafe_correction_with_disable_uncorrectable? | Whether a correction exists but is skipped because it is unsafe in a safe autocorrect run, while |
| #contextual_autocorrect_held_back? | When LSP is enabled or the |
Instance Method Summary
-
#on_csend(node)
Alias for #on_send.
- #on_send(node) (also: #on_csend)
- #to_method(node)
- #to_method_symbol(node)
- #allow_receiver?(receiver) ⇒ Boolean private
- #allowed_method_name?(name) ⇒ Boolean private
- #conversion_method?(method_name) ⇒ Boolean private
- #conversion_removes_content?(node, receiver) ⇒ Boolean private
- #correct_method(node, receiver) private
- #correct_sym_method(to_method) private
- #current_method(node, receiver, to_method) private
- #handle_as_symbol(node) private
- #handle_conversion_method(node) private
- #ignored_class?(name) ⇒ Boolean private
- #ignored_classes private
- #remove_parentheses(corrector, node) private
- #safe_navigation?(node) ⇒ Boolean private
- #top_receiver(node) private
::RuboCop::Cop::AllowedPattern - Included
| #allowed_line?, #allowed_pattern_regexps, #allowed_patterns, #cop_config_deprecated_methods_values, #cop_config_patterns_values, #ignored_line?, #matches_allowed_pattern?, #matches_ignored_pattern? |
::RuboCop::Cop::AllowedMethods - Included
::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 | — grouped under the Commissioner heading above. |
| #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: |
| #file_independent_relevance | Whether |
| #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 The source is parsed the way the file under investigation was. |
| #parser_engine, | |
| #ready | Called between investigations. |
| #relevant_file?, | |
| #target_gem_version | Returns the version of a gem in the target, by default its locked version (i.e. from Gemfile.lock or gems.locked). |
| #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, #covering_disabled_range, #current_corrector, | |
| #current_offense_locations | Reserved for Commissioner: |
| #current_offenses, #currently_disabled_lines, #custom_severity, #default_severity, #disable_uncorrectable, #enabled_line?, | |
| #enabled_lines? | A multi-line offense is suppressed by a directive on any line of its range, not only its first line, matching the intuition that the directive is attached to the offending code. |
| #file_name_matches_any?, #find_message, #find_severity, #matches_absolute_include_pattern?, #new_offense, #range_for_original, #range_from_node_or_range, | |
| #reset_investigation | Actually private methods. |
| #suppression_reason | The |
| #use_corrector | |
::RuboCop::Cop::AutocorrectLogic - Included
::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/lint/number_conversion.rb', line 91
def self.autocorrect_incompatible_with [Style::MethodCallWithArgsParentheses, Style::NestedParenthesizedCalls] end
Instance Method Details
#allow_receiver?(receiver) ⇒ Boolean (private)
# File 'lib/rubocop/cop/lint/number_conversion.rb', line 189
def allow_receiver?(receiver) if receiver.numeric_type? || (receiver.call_type? && (conversion_method?(receiver.method_name) || allowed_method_name?(receiver.method_name))) true elsif (receiver = top_receiver(receiver)) receiver.const_type? && ignored_class?(receiver.const_name) else false end end
#allowed_method_name?(name) ⇒ Boolean (private)
# File 'lib/rubocop/cop/lint/number_conversion.rb', line 201
def allowed_method_name?(name) allowed_method?(name) || matches_allowed_pattern?(name) end
#conversion_method?(method_name) ⇒ Boolean (private)
# File 'lib/rubocop/cop/lint/number_conversion.rb', line 211
def conversion_method?(method_name) CONVERSION_METHODS.include?(method_name) end
#conversion_removes_content?(node, receiver) ⇒ Boolean (private)
# File 'lib/rubocop/cop/lint/number_conversion.rb', line 138
def conversion_removes_content?(node, receiver) return false if receiver.last_line == node.last_line range = receiver.source_range.end.join(node.source_range.end) processed_source.tokens_within(range).any? do |token| token.comment? || token.type == :tSTRING_END end end
#correct_method(node, receiver) (private)
[ GitHub ]# File 'lib/rubocop/cop/lint/number_conversion.rb', line 166
def correct_method(node, receiver) format(CONVERSION_METHOD_CLASS_MAPPING[node.method_name], number_object: receiver.source) end
#correct_sym_method(to_method) (private)
[ GitHub ]# File 'lib/rubocop/cop/lint/number_conversion.rb', line 170
def correct_sym_method(to_method) body = format(CONVERSION_METHOD_CLASS_MAPPING[to_method], number_object: 'i') "{ |i| #{body} }" end
#current_method(node, receiver, to_method) (private)
[ GitHub ]#handle_as_symbol(node) (private)
[ GitHub ]# File 'lib/rubocop/cop/lint/number_conversion.rb', line 147
def handle_as_symbol(node) to_method_symbol(node) do |receiver, sym_node, to_method| next if receiver.nil? || !node.arguments.one? || node.operator_method? = format( MSG, current: sym_node.source, corrected_method: correct_sym_method(to_method) ) add_offense(node, message: ) do |corrector| next if part_of_ignored_node?(node) remove_parentheses(corrector, node) if node.parenthesized? corrector.replace(sym_node, correct_sym_method(to_method)) end end end
#handle_conversion_method(node) (private)
[ GitHub ]# File 'lib/rubocop/cop/lint/number_conversion.rb', line 118
def handle_conversion_method(node) to_method(node) do |receiver, to_method| next if receiver.nil? || allow_receiver?(receiver) = format( MSG, current: current_method(node, receiver, to_method), corrected_method: correct_method(node, receiver) ) add_offense(node, message: ) do |corrector| next if (node) || part_of_ignored_node?(node) next if conversion_removes_content?(node, receiver) corrector.replace(node, correct_method(node, node.receiver)) ignore_node(node) end end end
#ignored_class?(name) ⇒ Boolean (private)
# File 'lib/rubocop/cop/lint/number_conversion.rb', line 219
def ignored_class?(name) ignored_classes.include?(name.to_s) end
#ignored_classes (private)
[ GitHub ]# File 'lib/rubocop/cop/lint/number_conversion.rb', line 215
def ignored_classes cop_config.fetch('AllowedClasses', []) end
#on_csend(node)
Alias for #on_send.
# File 'lib/rubocop/cop/lint/number_conversion.rb', line 114
alias on_csend on_send
#on_send(node) Also known as: #on_csend
[ GitHub ]# File 'lib/rubocop/cop/lint/number_conversion.rb', line 110
def on_send(node) handle_conversion_method(node) handle_as_symbol(node) end
#remove_parentheses(corrector, node) (private)
[ GitHub ]# File 'lib/rubocop/cop/lint/number_conversion.rb', line 180
def remove_parentheses(corrector, node) corrector.replace(node.loc.begin, ' ') corrector.remove(node.loc.end) end
#to_method(node)
[ GitHub ]# File 'lib/rubocop/cop/lint/number_conversion.rb', line 96
def_node_matcher :to_method, <<~PATTERN (call $_ ${#{METHODS}}) PATTERN
#to_method_symbol(node)
[ GitHub ]#top_receiver(node) (private)
[ GitHub ]# File 'lib/rubocop/cop/lint/number_conversion.rb', line 205
def top_receiver(node) receiver = node receiver = receiver.receiver until receiver.receiver.nil? receiver end