Ruby style guide

This is a GitLab-specific style guide for Ruby code. Everything documented in this page can bereopened for discussion.

We useRuboCop to enforce Ruby style guide rules.

Where a RuboCop rule is absent, refer to the following style guides as general guidelines to write idiomatic Ruby:

Generally, if a style is not covered by existing RuboCop rules or the above style guides, it shouldn’t be a blocker.

Some styles we have decidedno one should not have a strong opinion on.

See also:

Styles we have no rule for

These styles are not backed by a RuboCop rule.

For every style added to this section, link the discussion from the section’shistory note to provide context and serve as a reference.

Instance variable access usingattr_reader

Instance variables can be accessed in a variety of ways in a class:

# publicclassFooattr_reader:my_vardefinitialize(my_var)@my_var=my_varenddefdo_stuffputsmy_varendend# privateclassFoodefinitialize(my_var)@my_var=my_varendprivateattr_reader:my_vardefdo_stuffputsmy_varendend# directclassFoodefinitialize(my_var)@my_var=my_varendprivatedefdo_stuffputs@my_varendend

Public attributes should only be used if they are accessed outside of the class.There is not a strong opinion on what strategy is used when attributes are onlyaccessed internally, as long as there is consistency in related code.

Newlines style guide

In addition to the RuboCop’sLayout/EmptyLinesAroundMethodBody andCop/LineBreakAroundConditionalBlock that enforce some newline styles, we have the following guidelines that are not backed by RuboCop.

# baddefmethodissue=Issue.newissue.saverenderjson:issueend
# gooddefmethodissue=Issue.newissue.saverenderjson:issueend

Rule: newline before block

# baddefmethodissue=Issue.newifissue.saverenderjson:issueendend
# gooddefmethodissue=Issue.newifissue.saverenderjson:issueendend
Exception: no need for a newline when code block starts or ends right inside another code block
# baddefmethodifissueifissue.valid?issue.saveendendend
# gooddefmethodifissueifissue.valid?issue.saveendendend

Method ordering within classes

For ordering methods at the class level (public, protected, private sections), refer toRuboCop’sLayout/ClassStructure.

Within each visibility section, consider the following principles to improve readability:

Rule: Order methods by level of abstraction (high-level before low-level)

Methods should generally be ordered from highest to lowest level of abstraction. This means:

  • Methods that orchestrate or coordinate work should come first
  • Helper methods that support those orchestrator methods should come after

This follows the“newspaper style”or“stepdown rule” principle,where code reads like a story from top to bottom,with the most important operations first and implementation details revealed progressively.

# good - orchestrator method before helpersclassCommitMessageProcessordefexecuteother_method_callsprocess_commit_messageendprivatedefprocess_commit_messagetitle=extract_title(commit.message)body=extract_body(commit.message)# ... process title and bodyenddefextract_title(message)message.split("\n").firstenddefextract_body(message)message.split("\n")[1..]endend
# bad - helper methods before the method that uses themclassCommitMessageProcessordefexecuteother_method_callsprocess_commit_messageendprivatedefextract_title(message)message.split("\n").firstenddefextract_body(message)message.split("\n")[1..]enddefprocess_commit_messagetitle=extract_title(commit.message)body=extract_body(commit.message)# ... process title and bodyendend

This ordering helps readers understand:

  • What the code does (by reading the high-level method first)
  • How it does it (by reading the helper methods after)

Following this ordering pattern helps reviewers and future maintainers understand code flow more quickly,especially in service objects, processors, and other classes with clear orchestration patterns.

Exceptions to this ordering may be appropriate when:

  • Methods are grouped by a domain concept that’s more important than abstraction level
  • Alphabetical ordering provides significant value for a large number of similar methods

When a class has multiple high-level methods that serve different, unrelated purposes,group each high-level method with its supporting helper methods. Alternatively, consider extractingthe implementation into separate service classes where each class has a single clear responsibility.

Beyond two levels of method calls (a method calling a method calling a method),this pattern can become unwieldy and hard to follow. If you find yourself with deep nesting,consider refactoring into separate classes or simplifying the logic.

Rails / ActiveRecord

This section contains GitLab-specific guidelines for Rails and ActiveRecord usage.

Avoid ActiveRecord callbacks

ActiveRecord callbacks allowyou to “trigger logic before or after an alteration of an object’s state.”

Use callbacks when no superior alternative exists, but employ them only if youthoroughly understand the reasons for doing so.

When adding new lifecycle events for ActiveRecord objects, it is preferable toadd the logic to a service class instead of a callback.

Why callbacks should be avoided

In general, callbacks should be avoided because:

  • Callbacks are hard to reason about because invocation order is not obvious andthey break code narrative.
  • Callbacks are harder to locate and navigate because they rely on reflection totrigger rather than being ordinary method calls.
  • Callbacks make it difficult to apply changes selectively to an object’s statebecause changes always trigger the entire callback chain.
  • Callbacks trap logic in the ActiveRecord class. This tight coupling encouragesfat models that contain too much business logic, which could instead live inservice objects that are more reusable, composable, and are easier to test.
  • Illegal state transitions of an object can be better enforced throughattribute validations.
  • Heavy use of callbacks affects factory creation speed. With some classeshaving hundreds of callbacks, creating an instance of that object foran automated test can be a very slow operation, resulting in slow specs.

Some of these examples are discussed in thisvideo from thoughtbot.

The GitLab codebase relies heavily on callbacks and it is hard to refactor themonce added due to invisible dependencies. As a result, this guideline does notcall for removing all existing callbacks.

When to use callbacks

Callbacks can be used in special cases. Some examples of cases where adding acallback makes sense:

  • A dependency uses callbacks and we would like to override the callbackbehavior.
  • Incrementing cache counts.
  • Data normalization that only relates to data on the current model.

Example of moving from a callback to a service

There is a project with the following basic data model:

classProjecthas_one:repositoryendclassRepositorybelongs_to:projectend

Say we want to create a repository after a project is created and use theproject name as the repository name. A developer familiar with Rails mightimmediately think: sounds like a job for an ActiveRecord callback! And add thiscode:

classProjecthas_one:repositoryafter_initialize:create_random_nameafter_create:create_repositorydefcreate_random_nameSecureRandom.alphanumericenddefcreate_repositoryRepository.create!(project:self)endendclassRepositoryafter_initialize:set_namedefset_namename=project.nameendendclassProjectsControllerdefcreateProject.create!# also creates a repository and names itendend

While this seems pretty harmless for a baby Rails app, adding this type of logicvia callbacks has many downsides once your Rails app becomes large and complex(all of which are listed in this documentation). Instead, we can add thislogic to a service class:

classProjecthas_one:repositoryendclassRepositorybelongs_to:projectendclassProjectCreatordefself.executeApplicationRecord.transactiondoname=SecureRandom.alphanumericproject=Project.create!(name:name)Repository.create!(project:project,name:name)endendendclassProjectsControllerdefcreateProjectCreator.executeendend

With an application this simple, it can be hard to see the benefits of the secondapproach. But we already some benefits:

  • Can testRepository creation logic separate fromProject creation logic. Codeno longer violates law of demeter (Repository class doesn’t need to knowproject.name).
  • Clarity of invocation order.
  • Open to change: if we decide there are some scenarios where we do not want arepository created for a project, we can create a new service class ratherthan needing to refactor toProject andRepository classes.
  • Each instance of aProject factory does not create a second (Repository) object.

ApplicationRecord / ActiveRecord model scopes

When creating a new scope, consider the following prefixes.

for_

For scopes which filterwhere(belongs_to: record).For example:

scope:for_project,->(project){where(project:project)}Timelogs.for_project(project)

with_

For scopes whichjoins,includes, or filterswhere(has_one: record) orwhere(has_many: record) orwhere(boolean condition)For example:

scope:with_labels,->{includes(:labels)}AbuseReport.with_labelsscope:with_status,->(status){where(status:status)}Clusters::AgentToken.with_status(:active)scope:with_due_date,->{where.not(due_date:nil)}Issue.with_due_date

It is also fine to use custom scope names, for example:

scope:undeleted,->{where('policy_index >= 0')}Security::Policy.undeleted

order_by_

For scopes whichorder.For example:

scope:order_by_name,->{order(:name)}Namespace.order_by_namescope:order_by_updated_at,->(direction=:asc){order(updated_at:direction)}Project.order_by_updated_at(:desc)

Styles we have no opinion on

If a RuboCop rule is proposed and we choose not to add it, we should document that decision in this guide so it is more discoverable and link the relevant discussion as a reference.

Quoting string literals

Due to the sheer amount of work to rectify, we do not care whether stringliterals are single or double-quoted.

Previous discussions include:

Individual groups maychoose to have an opinion on consistency of quoting styles within thebounded contexts they own, but these decisions only apply to code within that context.

Type safety

Now that we’ve upgraded to Ruby 3, we have more options availableto enforcetype safety.

Some of these options are supported as part of the Ruby syntax and do not require the use of specific type safety tools likeSorbet orRBS. However, we might consider these tools in the future as well.

For now, we can useYARD annotations to define types.IDEs such as RubyMine provide support for YARD when showing type-based inspection errors.

For more information, seeType safety in theremote_development domain README.

Functional patterns

Although Ruby and especially Rails are primarily based onobject-oriented programming patterns, Ruby is a very flexible language and supportsfunctional programming patterns as well.

Functional programming patterns, especially in domain logic, can often result in more readable, maintainable, and bug-resistant code while still using idiomatic and familiar Ruby patterns.However, functional programming patterns should be used carefully because some patterns would cause confusion and should be avoided even if they’re directly supported by Ruby. Thecurry method is a likely example.

For more information, see: