Is Rubocop a superset of the "ruby -c" syntax check? - ruby

We had a test that found every Ruby file in our application and ran ruby -c on it. We introduced Rubocop and made it check the same list of files.
Is the test that ran ruby -c actually now useless, or is there an example of a failure mode that would be caught by ruby -c but not Rubocop?
The documentation for ruby -c says:
Causes Ruby to check the syntax of the script and exit without executing. If there are no syntax errors, Ruby will print "Syntax OK" to the standard output.
This is an example of a syntax issue that will be caught by either:
% echo "puts 'hello world" > hot_script.rb
% ruby -c hot_script.rb
hot_script.rb:1: unterminated string meets end of file
% rubocop hot_script.rb
Inspecting 1 file
F
Offenses:
hot_script.rb:1:6: F: unterminated string meets end of file
(Using Ruby 1.9 parser; configure using TargetRubyVersion parameter, under AllCops)
puts 'hello world
^
1 file inspected, 1 offense detected
Rubocop even catches some of the same warnings, though I didn't have ruby -c configured to catch these previously, and I am therefore more interested in errors. Here's an example of relative parity in handling a warning:
% cat unused_var.rb
def hot_method
a = 1
b = 2
puts b
end
% ruby -cwW2 unused_var.rb
unused_var.rb:2: warning: assigned but unused variable - a
Syntax OK
% rubocop unused_var.rb
Inspecting 1 file
W
Offenses:
unused_var.rb:2:3: W: Lint/UselessAssignment: Useless assignment to variable - a.
a = 1
^
1 file inspected, 1 offense detected
I searched using
https://www.google.com/search?q=rubocop%20syntax%20check%20superset
https://www.google.com/search?q=is%20there%20any%20reason%20to%20run%20ruby%20-c%20syntax%20check%20if%20i%20use%20rubocop
but I may be doing it wrong. The test is way slower in Ruby 1.9 than it was in Ruby 1.8, so the answer to this question is actually valuable to me. And you have to admit, you're curious, right?

The answer is "most of the time." RuboCop builds on the parser gem, which is a standalone Ruby parser which mimics, more or less, the MRI parser. RuboCop wraps parser's syntax checks and will properly report issues. However, as stated on the parser's GitHub:
Unfortunately MRI often changes syntax in patch level versions
[...] there is no simple way to track these changes.
This policy makes it all but impossible to make Parser precisely
compatible with the Ruby MRI parser.
In addition, parser supports the latest minor version of whatever release you are using, and doesn't backport minor versions. So if you use Ruby 2.4.0, RuboCop will use a parser version supporting 2.4.1 syntax.
For all intents and purposes, parser is equivalent to the official MRI parser, and unless you have a specific reason to use both, using RuboCop alone should be sufficient.

Rubocop will also identify and report syntax errors since the code cannot be properly parsed if that is the case, so there's no need for both.

Related

Workaround "flip-flop deprecated" warning in Ruby

I invoke Ruby from my shell script like this:
ruby -n -e "print if %r($fromre)...%r($tore)" "$#"
Since Ruby 2.6, I get the warning
warning: flip-flop is deprecated
So it seems that i have to be prepared that the wise high priests of Ruby have decided that this (IMO useful) construct will be completely gone one day.
What would be an easy work-around? Of course I can replace
print if %r($fromre)...%r($tore)
by
inside ||= %r($fromre)
if inside
print
inside = false if %r($tore)
end
but I wonder whether there is a more concise way to write this.

Ruby: magic comments "frozen_string_literal: true" vs "immutable: string"

In ruby one can freeze all constant strings in a file via two different magic comments at the beginning of a file:
# frozen_string_literal: true
and
# -*- immutable: string -*-
I have no idea what the differences are.
Are there any?
The 1st syntax is the magic comment for Ruby 2.3+ versions to freeze string literals, otherwise you have to use the String method like this:
'hello world!'.freeze
The 2nd syntax is not implemented in Ruby, however it is the way that variables are specified for files in the Emacs text editor.
For example, the following comment in Emacs would declare that the file is a Ruby file and needs Ruby syntax highlighting, and that the variable immutable is set to the value string.
# -*- mode: ruby; immutable: string -*-
After searching around, it looks like that does nothing and is not used by any Ruby syntax highlighting mode.
So you do not need the 2nd syntax.
Digging for anything on the 2nd version, it looks like they had the same intention but the 2nd magic comment syntax does not to appear to have been adopted as of Ruby 2.1.0.
See https://github.com/ruby/ruby/pull/487
The first version # frozen_string_literal: true was adopted in Ruby 2.3.0
I tried the latter version in a few versions of ruby but didn't work. I would guess it should not be used or trusted to work in any version of >= 2.3 but probably no versions support it. In fact, I was not able to find any reference to that version in the open source code on github searching that syntax
https://github.com/ruby/ruby/search?q=immutable%3A+string&unscoped_q=immutable%3A+string

Ruby: Why do I get warning "regex literal in condition" here?

A simple Ruby program, which works well (using Ruby 2.0.0):
#!/usr/bin/ruby
while gets
print if /foo/../bar/
end
However, Ruby also outputs the warning warning: regex literal in condition. It seems that Ruby considers my flip-flop-expression /foo/../bar/ as dangerous.
My question: Where lies the danger in this program? And: Can I turn off this warning (ideally only for this statement, keeping other warnings active)?
BTW, I found on the net several discussions of this kind of code, also mentioning the warning, but never found a good explanation why we get warned.
You can avoid the warning by using an explicit match:
while gets
print if ~/foo/..~/bar/
end
Regexp#~ matches against $_.
I don't know why the warning is shown (to be honest, I wasn't even aware that Ruby matches regexp literals against $_ implicitly), but according to the parser's source code, it is shown unless you provide the -e option when invoking Ruby, i.e. passing the script as an argument:
$ ruby -e "while gets; print if /foo/../bar/ end"
I would avoid using $_ as an implicit parameter and instead use something like:
while line = gets
print line if line=~/foo/..line=~/bar/
end
I think Neil Slater is right: It looks like a bug in a parser. If I change the code to
#!/usr/bin/ruby
while gets
print if $_=~/foo/..$_=~/bar/
end
the warning disappears.
I'll file a bug report.

Is there a quick way to find missing end’s in Ruby?

syntax error, unexpected $end, expecting keyword_end
We’ve all been there! Assuming enough code changed that a quick glance at git diff or the like doesn’t make it obvious, is there an easy way to find that missing end (short of switching to an indentation-based language like Python)?
FWIW, I use Sublime Text 2 as my editor.
If you're using Ruby 1.9, try the -w flag when running your ruby program.
# t.rb
class Example
def meth1
if Time.now.hours > 12
puts "Afternoon"
end
def meth2
# ...
end
end
ruby t.rb
=> t.rb:10: syntax error, unexpected $end, expecting keyword_end
ruby -w t.rb
=> t.rb:5: warning: mismatched indentations at 'end' with 'if' at 3
t.rb:9: warning: mismatched indentations at 'end' with 'def' at 2
t.rb:10: syntax error, unexpected $end, expecting keyword_end
Source:
http://pragdave.blogs.pragprog.com/pragdave/2008/12/ruby-19-can-check-your-indentation.html
Edit (2023): this is now part of Ruby 3.2 and doesn‘t need to be required separately!
————————————
Edit (2022): the gem is now called syntax_suggest and is part of the Ruby standard library!
————————————
Since December 2020, there is also the dead_end gem which helps you detect missing ends.
The easiest way to get started is to install the gem:
gem install dead_end
and run it directly from your console, providing the file name to scan:
dead_end myfile.rb
This will provide you with a more helpful error message:
43 if (col_idx - 1) % 3 == 0
50 if !contains?(doc, node)
❯ 51 doc.add_child(node)
❯ 52 tree.
53 end
54 end
See the documentation for more options.
If you're using rails, you can run the problematic file specifically with the -w flag.
If you still can't find the offending mismatch, then my go-to way of solving this problem is just commenting out chunks of code until I can isolate the problematic area.
On OS X you can use command + / to comment out the highlighted piece of text.

Ruby 1.9 -Ku, mem_cache_store and invalid multibyte escape error

Originally this bug was posted here: https://rails.lighthouseapp.com/projects/8994/tickets/5713-ruby-19-ku-incompatible-with-mem_cache_store
And now, as we've run into the same issue, I'll copy here a question from that issue, hoping someone have an answer already:
When Ruby 1.9 is started in unicode mode (-Ku), mem_cache_store.rb fails to parse:
/usr/local/ruby19/bin/ruby -Ku /usr/local/ruby-1.9.2-p0/lib/ruby/gems/1.9.1/gems/
activesupport-3.0.0/lib/active_support/cache/mem_cache_store.rb
/usr/local/ruby-1.9.2-p0/lib/ruby/gems/1.9.1/gems/activesupport-3.0.0/lib/active_support/
cache/mem_cache_store.rb:32: invalid multibyte escape: /[\x00-\x20%\x7F-\xFF]/
Our case is practically identical: when you set config.action_controller.cache_store to :mem_cache_store, and try to run tests, console, or server, you recieve this in return:
/Users/%username%/.rvm/gems/ruby-1.9.2-p0/gems/activesupport-3.0.1/lib/active_support/
cache/mem_cache_store.rb:32: invalid multibyte escape: /[\x00-\x20%\x7F-\xFF]/
Any ideas how this can be avoided?..
Ruby 1.9 in unicode mode will attempt to interpret the regular expression as unicode. To avoid this you need to pass the regular expression option "n" for "no encoding":
ESCAPE_KEY_CHARS = /[\x00-\x20%\x7F-\xFF]/n
Now we have our raw 8-bit encoding (the only thing Ruby 1.8 speaks) as intended:
ruby-1.9.2-p136 :001 > ESCAPE_KEY_CHARS = /[\x00-\x20%\x7F-\xFF]/n.encoding
=> # <Encoding:ASCII-8BIT>
Hopefully the Rails teams fixes this, for now you have to edit the file.

Resources