Define keyword arguments when defining methods with boolean arguments

When calling methods with boolean arguments does not explain what exactly is the argument about. Rubocop has a cop that suggests to define keyword arguments when defining methods with boolean arguments.

Let’s consider an example.

def feature_status(is_admin = false)
  if is_admin
    puts "feature is enabled"
  else
    puts "feature is disabled"
  end
end

Now, whenever we have to call such method, it’ll be something like

feature_status(true)

Now, by looking at the code given above, it is not very much clear what that argument is about.

Thus, Rubocop has introduced a cop to define these boolean arguments as keyword arguments.

The same method given above can be written as

def feature_status(is_admin: false)
  if is_admin
    puts "feature is enabled"
  else
    puts "feature is disabled"
  end
end

This can be called as given below.

feature_status(is_admin: true)

As we can see, it is pretty clear what that argument is about. It’ll be easier to understand what argument needs to passed here precisely.

Allowed mehthods

Rubocop has made it possible to allow some methods if you want to make an exception for this rule. It can be defined as given below.

allowed_methods: ['feature_status']

If this configuration is set in .rubocop.yml, it won’t give a warning for the method feature_status with boolean argument anymore.

akshay

Akshay Mohite

Hi there! I am a Ruby on Rails & ReactJS Enthusiast, building some cool products at DTree Labs.

Read More
Buy me a coffee