Manual:Coding conventions/Ruby


This article describes the coding conventions for Ruby files of MediaWiki related codebases.

Unlike Python with its PEP 8, Ruby has no truly canonical style guide to which to reference. There are, however, a few well respected guides that can serve as reference points for Rubyists, most prominently those from GitHub, Heroku, and the community-driven guide from bbatsov.

Starting point

edit

For reasons both public-spirited and practical, we have adopted the bbatsov guide as a starting point; it's the most participatory of the three and comes with the rubocop code analyzer that can be easily customized and integrated into our continuous integration.

Exceptions

edit

There are a handful of areas where the bbatsov guide attempts to draw the line with seemingly arbitrary limits or where there's quite a bit of disagreement among commenters. In most of these cases, we've opted to simply ignore the rules and defer in good faith to the developer.

Exceptions and additions to the bbatsov guide are enumerated herein.

Method length

edit
RuboCop ID
Metrics/MethodLength
Enforced
no

In general, developers should follow the single responsibility principle, but the bbatsov guide's 10-line limit seems rather arbitrary.[1]

Line length

edit
RuboCop ID
Metrics/LineLength
Enforced
yes, but at a 100 character limit

It's suggested in the bbatsov guide that lines should never exceed 80 characters in length, but there's an ongoing debate over it.[2][3] In fact, statistical analysis of the ten most popular Ruby projects on GitHub shows that a limit of 80 would invalidate more than 8% of existing lines while a more liberal limit of 100 or 120 would only invalid around 3% and 1% respectively.[4] Falling back on our own general coding conventions, 100 lines will be our current limit.

Multi-line method chaining

edit
RuboCop ID
Style/DotPosition
Enforced
per project

Two options are presented in the bbatsov guide.[5] We allow either form as long as you stay consistent within each project.

things.map { |thing| thing.age }.
  reduce { |sum, age| sum + age }

Also OK

edit
things.map { |thing| thing.age }
  .reduce { |sum, age| sum + age }

Signaling exceptions

edit
RuboCop ID
Style/SignalException
Enforced
no

The bbatsov guide suggests using fail to signal new exceptions and raise to re-raise rescued ones.[6] However, there's some objection to the rule based on the lack of the former in existing Ruby projects or prominent Ruby literature, and the contrived nature of useful semantic differences given as a justification.[7] For now, we don't enforce this rule.

def foo
  # ...

  raise "warning!" if error_condition_one?
  raise "oops. something terrible has happened" if error_condition_two?

  # ...
end

begin
  foo
rescue => exception
  raise unless exception.message.start_with?("warning!")
end

Aliasing methods

edit
RuboCop ID
Style/Alias
Enforced
no

The bbatsov guide suggests that alias_method should always be used over alias.[8] However, there are cases where alias can be just as clear or even more appropriate when written alongside methods defined with def.[9]

In short, it's ok to use alias within the body of a class or module definition to alias a method also defined therein, but it should not be used to alias methods defined by a macro; alias_method is more appropriate in that case since it's a macro itself.

Good

edit
class List
  attr_reader :length
  alias_method :size, :length

  def fold_left(&accumulator)
    # yield left to right (head to tail)
  end

  def fold_right(&accumulator)
    # yield right to left (tail to head)
  end

  alias fold fold_left
end
class List
  attr_reader :length
  alias size length

  def fold_left(&accumulator)
    # yield left to right (head to tail)
  end

  def fold_right(&accumulator)
    # yield right to left (tail to head)
  end

  alias_method :fold, :fold_left
end

String literals

edit
RuboCop ID
Style/StringLiterals
Enforced
per project

Either single or double quotes are acceptable defaults for string literals, as long as you stay consistent within projects. Unlike in PHP, the Ruby implementation of string literals yields identical runtime performance between the two forms.

Trivial attribute methods

edit
RuboCop ID
Style/TrivialAccessors
Enforced
yes, but using the ExactNameMatch option

The bbatsov guide discourages methods that amount to simple attribute accessors, suggesting use of attr macros instead.[10] While the use of attribute macros is generally common practice among Ruby developers, the rule's default options don't allow for methods that expose variables of a different name.

Good

edit
class List
  attr_reader :length
end

class List
  def length
    @size
  end
end
class List
  def length
    @length
  end
end

RuboCop

edit

RuboCop check is enabled for MediaWiki and related repos that contain Ruby code, enforcing the conventions outlined here. In most cases, a configuration file has been initialized using the --auto-gen-config option; the generated config will ignore all violations by default, allowing maintainers to address them one by one.

Ignoring or customizing RuboCop rules

edit

When you want to ignore a rule or customize its behavior, whether you're going by the recommendations in this guide or not, you'll need to add some configuration to the .rubocop.yml file in the project's root directory (after the inherit_from: entry).

For example, to ignore the Metrics/LineLength rule altogether, you'd add the following.

Metrics/LineLength:
  Enable: false

To customize it to using a more liberal line length limit, say 120, you'd add this.

Metrics/LineLength:
  Max: 120

Please consult the RuboCop documentation for possible rule names and options.

Base configuration

edit

Following is a RuboCop configuration that reflects the exceptions above. Please use it as a starting point for your Ruby projects.

AllCops:
  # Only enforce rules that have an entry in the style guide
  StyleGuideCopsOnly: true

Metrics/LineLength:
  Max: 100

Metrics/MethodLength:
  Enabled: false

Style/Alias:
  Enabled: false

Style/SignalException:
  Enabled: false

# Pick one and stay consistent
Style/StringLiterals:
  EnforcedStyle: single_quotes
#  EnforcedStyle: double_quotes

Style/TrivialAccessors:
  ExactNameMatch: true

References

edit
  1. Single Responsibility Principle, Wikipedia [1]
  2. The Ruby Style Guide, Source Code Layout, bbatsov [2]
  3. The Ruby Style Guide, Issue #207 [3]
  4. The Ruby Style Guide, Issue #207, lee-dohm [4]
  5. The Ruby Style Guide, Multi-line Method Chains, bbatsov [5]
  6. The Ruby Style Guide, Fail Method, bbatsov [6]
  7. The Ruby Style Guide, Issue #233 [7]
  8. The Ruby Style Guide, bbatsov [8]
  9. The Ruby Style Guide, Issue #377 [9]
  10. The Ruby Style Guide, bbatsov [10]