11 Most Asked Questions About RuboCop
Tags: ruby, rails
Published: 2020-06-26 07:30:29

RuboCop is a Ruby static code analyzer and code formatter which helps to track errors easily and fix minor code issues during the development process saving your time. It has many advantages and you can learn more about RuboCop on https://docs.rubocop.org/en/stable/.

Today, we will be talking about the most asked questions about RuboCop.

## 11 Most Asked Questions About RuboCop

### 1. How to check if record exists from controller in Rails

**Answer:**

**How to test if at least one record exists?**

**Option 1:** Using <a herf="https://apidock.com/rails/ActiveRecord/FinderMethods/exists%3f">`.exists?`</a>

```
if Business.exists?(user_id: current_user.id)
  # same as Business.where(user_id: current_user.id).exists?
  # ...
else
  # ...
end
```

**Option 2:** Using `.present?` (or `.blank?`, the opposite of `.present?`)

```
if Business.where(:user_id => current_user.id).present?
  # less efficiant than using .exists? (see generated SQL for .exists? vs .present?)
else
  # ...
end
```

**Option 3:** Variable assignment in the if statement

```
if business = Business.where(:user_id => current_user.id).first
  business.do_some_stuff
else
  # do something else
end
```

This option can be considered a code smell by some linters (RuboCop for example).

**Option 3b:** Variable assignment

```
business = Business.where(user_id: current_user.id).first
if business
  # ...
else
  # ...
end
```

You can also use `.find_by_user_id(current_user.id)` instead of `.where(...).first`

**Best option:**

- If you don’t use the `Business` object(s): **Option 1**
- If you need to use the `Business` object(s): **Option 3**

**Alternative Answer:**

In this case, you can use the `exists?` method provided by ActiveRecord:

```
Business.exists? user_id: current_user.id
```

### 2. How to ignore lines with comments?

**Answer:**

There is a way to ignore cops on a per-line basis.

There is also a way to do it via the configuration file.

Run `rubocop --auto-gen-config` and it will generate a file that you can use to disable the offenses.

The command also gives a hint on what to do to load those options.

On a line per line basis, you can enable and disable the cops as well.

```
# rubocop:disable RuleByName
This is a long line 
# rubocop:enable RuleByName
```

You can also do more than one rule at a time in your code.

```
# rubocop:disable BlockComments, AsciiComments
```

By using an inline directive, the directive becomes valid only for that line, and it would look like this:

```
method(argument) # rubocop:disable SomeRule, SomeOtherRule
```

**Alternative Answer:**

It’s possible to define regex patterns to automatically ignore certain lines in `rubocop.yml`, so you could choose to ignore all lines starting with a `#` character:

```
Metrics/LineLength:
  Max: 80
  IgnoredPatterns: ['\A#']
```

This could be improved so that “indented” comment lines (i.e. whitespace followed by a `#` character) is also ignored if that’s what you want.

Note that this doesn’t account for lines of code that end with a comment, though:

```
some_code(that_does_something) # This line would NOT be ignored by Rubocop.
```

### 3. How to split Ruby regex over multiple lines?

**Answer:**

You need to use the `/x` modifier, which enables <a href="https://www.regular-expressions.info/freespacing.html">free-spacing mode.</a>

Like in this case:

```
"bar" =~ /(foo|
           bar)/x
```

**Alternative Answer:**

Using %r with the x option is the preferred way to do this.

See this example from the GitHub ruby style guide

```
regexp = %r{
  start         # some text
  \s            # white space char
  (group)       # first group
  (?:alt1|alt2) # some alternation
  end
}x

regexp.match? "start groupalt2end"
```

### 4. RuboCop: Line is too long ← How to Ignore?

**Answer:**

You can disable a bunch of lines like this:

```
# rubocop:disable LineLength
puts "This line is lonnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnng"
# rubocop:enable LineLength
```

Or add this to your `.rubocop.yml` file to increase the max length:

```
Metrics/LineLength:
  Max: 100
```

**Alternative Answer:**

Creating a `.rubocop.yml` file (keep an eye on the initial . in the filename) in the root of your project, you’ll have a bunch of options:

```
Metrics/LineLength:
  # This will disable the rule completely, regardless what other options you put
  Enabled: false
  # Change the default 80 chars limit value
  Max: 120
  # If you want the rule only apply to a specific folder/file
  Include:
    - 'app/**/*'
  # If you want the rule not to apply to a specific folder/file
  Exclude:
    - 'db/schema.rb'
```

### 5. What is meant by ‘Assignment Branch Condition Size too high’ and how to fix it?

**Answer:**

Assignment Branch Condition (ABC) size is a measurement of the size of a method. It is essentially determined by counting the number of **A**ssignments, **B**ranches, and **C**onditional statements.

To reduce the ABC score, you could move some of those assignments into before_action calls:

```
before_action :fetch_current_category, only: [:show,:edit,:update] 
before_action :fetch_categories, only: [:show,:edit,:update] 
before_action :fetch_search_results, only: [:show,:edit,:update] #or whatever

def show
  rate
end

private

def fetch_current_category
  @category = Category.friendly.find(params[:id])
end

def fetch_categories
  @categories = Category.all
end

def fetch_search_results
  @search = category.products.approved.order(updated_at: :desc).ransack(params[:q])
  @products = @search.result.page(params[:page]).per(50)
end
```

### 6. How to tell RuboCop to ignore a specific directory or file?

**Answer:**

You can add the following to .rubocop.yml:

```
AllCops:
  Exclude:
    - 'path/to/excluded/file.rb'
```

where the path is relative to .rubocop.yml

**Alternative Answer:**

From `rubocop/default.yml`:

```
AllCops:
  Exclude:
    - 'node_modules/**/*'
    - 'vendor/**/*'
```

### 7. How to integrate RuboCop with Rake?

**Answer:**

The simple answer is just adding this to your Rakefile:

```
task test: :rubocop

task :rubocop do
  sh 'rubocop'
end
```

**Alternative Answer:**

As of version `0.10.0` RuboCop contains a custom rake task that you can use. Just put the following in your `Rakefile`

```
require 'rubocop/rake_task'

RuboCop::RakeTask.new
```

Make sure to use upper-case ‘R’ and ‘C’ or you will get a NameError.

### 8. How to silence RuboCop warning on Assignment Branch Condition?

**Answer:**

This is the message for the <a href="https://github.com/rubocop-hq/rubocop/blob/ca377951bb2ba17184d5ea9fb1bc8842097de1c9/lib/rubocop/cop/metrics/abc_size.rb">Metrics/AbcSize cop.</a>

`# rubocop:disable Metrics/AbcSize`

**Alternative Answer:**

On your RuboCop config

```
Metrics/AbcSize:
  Enabled: false
```

### 9. How to disable frozen string literal comment checking?

**Answer:**

Add the following to your `.rubocop.yml`:

```
Style/FrozenStringLiteralComment:
  Enabled: false
```

### 10. How to pass &:key as an argument to map instead of a block with Ruby?

**Answer:**

Pass &:key as an argument to map instead of a block.

Meaning:

```
my.objects.map(&:key)
```

### 11. How to fix "SublimeLinter-RuboCop not running even when enabled and RuboCop in the path"?

**Answer:**

First, specify the right path for you ruby env in `Packages/User/SublimeLinter.sublime-settings` as this:

```
{
    ...
    "paths": {
        "linux": [],
        "osx": [
            "~/.rbenv/shims/"
        ],
        "windows": []
    },
    ...
}
```

After that close sublime completely and reopen it.

**In Conclusion**

These are the most asked questions about the RuboCop. If you have any suggestions or any confusion, please comment below. If you need any help, we will be glad to help you.

We, at <a href="https://www.truemark.dev/">Truemark</a>, provide services like web and mobile app development, digital marketing, and website development. So, if you need any help and want to work with us, please feel free to contact us.

Hope this article helped you.

Original Source: <a href="https://thedevpost.com/blog/11-most-asked-questions-about-rubocop/">DevPostbyTruemark</a>