Read more

Rubocop: Fix Style/SpecialGlobalVars

Avatar
Julian
March 10, 2023Software engineer at makandra GmbH

tl;dr

Don't forget require 'English' if you use a named global such as $LAST_MATCH_INFO. Otherwise this could result in an annoying bug.

Background

The code snippet of How to fix gsub on SafeBuffer objects was adjusted during a rubocop upgrade.

Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

Rubocop tells you everything you need to know to fix the offense Style/SpecialGlobalVars:

Style/SpecialGlobalVars: Prefer $LAST_MATCH_INFO from the stdlib 'English' module (don't forget to require it) over $~.

In this scenario you should be very careful. If you forget to require 'English', your code may not work any longer as expected.

# Before
Thread.current[:LAST_MATCH_DATA] = $~

# After rubocop ugrade - was not working as expected
Thread.current[:LAST_MATCH_DATA] = $LAST_MATCH_INFO

# Fixed
require 'English'

Thread.current[:LAST_MATCH_DATA] = $LAST_MATCH_INFO
Posted by Julian to makandra dev (2023-03-10 13:45)