Ruby. Messages from RuboCop about using predefined variables

Ruby has a lot of predefined variables. The one of them is $/. It is used as a universal substitution of newline symbol:

> numbers = ['one', 'two', 'three']
=> ["one", "two", "three"]

> numbers.join($/)
=> "one\ntwo\nthree"

> puts numbers.join($/)
one
two
three
=> nil
RuboCop is a Ruby code style checker (linter) and formatter based on the community-driven Ruby Style Guide. If you use it in your project, then it is possible that you will face with the next problem when using $/:
Prefer `$INPUT_RECORD_SEPARATOR` or `$RS` from the stdlib 'English' module
(don't forget to require it) over `$/`.(convention:Style/SpecialGlobalVars)
To fix it you can do like this:

# readable global var aliases
require 'English'

...
def log_error(error)
  backtrace_cleaner = ActiveSupport::BacktraceCleaner.new
  backtrace_cleaner.add_filter { |line| line.gsub(Rails.root.to_s, '') }
  backtrace_cleaner.add_silencer { |line| line =~ /puma|rubygems/ }

  Rails.logger.error(
    [
      "#{error.class}: #{error.message}",
      *backtrace_cleaner.clean(error.backtrace)
    ].join($RS)
  )
end
...

As you can see I have used the $RS. Instead, you can use $INPUT_RECORD_SEPARATOR.

No comments :

Post a Comment