class RuboCop::Cop::InternalAffairs::LocationExists
When a node location may not exist, ‘Node#loc?` or `Node#loc_is?` can be used instead of calling `Node#respond_to?` before using the value.
@example
# bad node.loc.respond_to?(:begin) && node.loc.begin # good node.loc?(:begin) # bad node.loc.respond_to?(:begin) && node.loc.begin.is?('(') # good node.loc_is?(:begin, '(') # bad node.loc.respond_to?(:begin) && node.loc.begin.source == '(' # good node.loc_is?(:begin, '(')
Constants
- MSG
Public Instance Methods
Source
# File lib/rubocop/cop/internal_affairs/location_exists.rb, line 63 def on_and(node) replace_with_loc(node) || replace_with_loc_is(node) end
Private Instance Methods
Source
# File lib/rubocop/cop/internal_affairs/location_exists.rb, line 110 def dot(node) node.parent.loc.dot.source end
Source
# File lib/rubocop/cop/internal_affairs/location_exists.rb, line 86 def register_offense(node, replacement) message = format(MSG, replacement: replacement, source: node.source) add_offense(node, message: message) do |corrector| corrector.replace(node, replacement) end end
Source
# File lib/rubocop/cop/internal_affairs/location_exists.rb, line 98 def replace_assignment(receiver, location) prefix = replace_receiver(receiver) "#{prefix}loc#{dot(receiver)}#{location.value} if #{prefix}loc?(#{location.source})" end
Source
# File lib/rubocop/cop/internal_affairs/location_exists.rb, line 104 def replace_receiver(receiver) return '' unless receiver "#{receiver.source}#{dot(receiver)}" end
Source
# File lib/rubocop/cop/internal_affairs/location_exists.rb, line 69 def replace_with_loc(node) replaceable_with_loc(node) do |receiver, location| if node.parent&.assignment? register_offense(node, replace_assignment(receiver, location)) else register_offense(node, replacement(receiver, "loc?(#{location.source})")) end end end
Source
# File lib/rubocop/cop/internal_affairs/location_exists.rb, line 79 def replace_with_loc_is(node) replaceable_with_loc_is(node) do |receiver, location, value| replacement = replacement(receiver, "loc_is?(#{location.source}, #{value.source})") register_offense(node, replacement) end end
Source
# File lib/rubocop/cop/internal_affairs/location_exists.rb, line 94 def replacement(receiver, rest) "#{replace_receiver(receiver)}#{rest}" end