Shopify’s Ruby Style Guide
Ruby is the main language at Shopify. We are primarily a Ruby shop and we are probably one of the largest out there. Ruby is the go-to language for new web projects and scripting.
We expect all developers at Shopify to have at least a passing understanding of Ruby. It's a great language. It will make you a better developer no matter what you work in day to day. What follows is a loose coding style to follow while developing in Ruby.
This Style Guide is the result of over a decade of Ruby development at Shopify. Much of its content is based on Bozhidar Batsov's Ruby Style Guide, adapted to Shopify by many contributors.
We recommend using RuboCop in your Ruby projects to help you adopt this Style Guide. To know how to install and use RuboCop please refer to RuboCop's official documentation.
We offer a default RuboCop configuration you can inherit from and be in sync
with this Style Guide. To use it, you can add this to your Gemfile:
gem "rubocop-shopify", require: falseAnd add to the top of your project's RuboCop configuration file:
inherit_gem:
rubocop-shopify: rubocop.ymlAny Include or Exclude configuration provided will be merged with RuboCop's defaults.
For more information about inheriting configuration from a gem please check RuboCop's documentation.
Make all lines of your methods operate on the same level of abstraction. (Single Level of Abstraction Principle)
Code in a functional way. Avoid mutation (side effects) when you can.
Overly defensive programming may safeguard against errors that will never be encountered, thus incurring run-time and maintenance costs.
Avoid mutating arguments.
Avoid monkeypatching.
Avoid long methods.
Avoid long parameter lists.
Avoid needless metaprogramming.
Prefer public_send over send so as not to circumvent private/protected
visibility.
Write ruby -w safe code.
Avoid more than three levels of block nesting.
Use UTF-8 as the source file encoding.
Use 2 space indent, no tabs.
Use Unix-style line endings.
Avoid using ; to separate statements and expressions. Use one
expression per line.
Use spaces around operators, after commas, colons and semicolons, around {
and before }.
Avoid spaces after (, [ and before ], ).
Avoid space after the ! operator.
Avoid space inside range literals.
Avoid space around method call operators.
# bad
foo . bar
# good
foo.barAvoid space in lambda literals.
# bad
a = -> (x, y) { x + y }
# good
a = ->(x, y) { x + y }Indent when as deep as the case line.
When assigning the result of a conditional expression to a variable, align its branches with the variable that receives the return value.
# bad
result =
if some_cond
# ...
# ...
calc_something
else
calc_something_else
end
# good
result = if some_cond
# ...
# ...
calc_something
else
calc_something_else
endWhen assigning the result of a begin block, align rescue/ensure/end with the start of the line
# bad
host = begin
URI.parse(value).host
rescue URI::Error
nil
end
# good
host = begin
URI.parse(value).host
rescue URI::Error
nil
endUse empty lines between method definitions and also to break up methods into logical paragraphs internally.
Use spaces around the = operator when assigning default values to method
parameters.
Avoid line continuation \ where not required.
Align the parameters of a method call, if they span more than one line, with one level of indentation relative to the start of the line with the method call.
# starting point (line is too long)
def send_mail(source)
Mailer.deliver(to: "[email protected]", from: "[email protected]", subject: "Important message", body: source.text)
end
# bad (double indent)
def send_mail(source)
Mailer.deliver(
to: "[email protected]",
from: "[email protected]",
subject: "Important message",
body: source.text)
end
# good
def send_mail(source)
Mailer.deliver(
to: "[email protected]",
from: "[email protected]",
subject: "Important message",
body: source.text,
)
endWhen chaining methods on multiple lines, indent successive calls by one level of indentation.
# bad (indented to the previous call)
User.pluck(:name)
.sort(&:casecmp)
.chunk { |n| n[0] }
# good
User
.pluck(:name)
.sort(&:casecmp)
.chunk { |n| n[0] }Align the elements of array literals spanning multiple lines.
Limit lines to 120 characters.
Avoid trailing whitespace.
Avoid extra whitespace, except for alignment purposes.
End each file with a newline.
Avoid block comments:
# bad
=begin
comment line
another comment line
=end
# good
# comment line
# another comment linePlace the closing method call brace on the line after the last argument when opening brace is on a separate line from the first argument.
# bad
method(
arg_1,
arg_2)
# good
method(
arg_1,
arg_2,
)Place each element/argument on a new line when wrapping a method call, hash, or array on multiple lines.
# bad
method(arg_1, arg_2,
arg_3
)
[
value_1, value_2,
value_3,
]
{
key1: value_1,
key2: value_2, key3: value_3,
}
# good
method(
arg_1,
arg_2,
arg_3,
)
[
value_1,
value_2,
value_3,
]
{
key1: value_1,
key2: value_2,
key3: value_3,
}
# good (special cases)
# Single argument method call
method({
foo: bar,
})
# Last argument, itself is multiline
class User
after_save :method, if: -> {
do_some_checks
}
end
# Single value array
errors = [{
error_code: 1234,
error_message: "This is an error",
}]
Separate magic comments from code and documentation with a blank line.
# good
# frozen_string_literal: true
# Some documentation for Person
class Person
# Some code
end
# bad
# frozen_string_literal: true
# Some documentation for Person
class Person
# Some code
endUse empty lines around attribute accessor.
# bad
class Foo
attr_reader :foo
def foo
# do something...
end
end
# good
class Foo
attr_reader :foo
def foo
# do something...
end
endAvoid empty lines around method, class, module, and block bodies.
# bad
class Foo
def foo
begin
do_something do
something
end
rescue
something
end
true
end
end
# good
class Foo
def foo
begin
do_something do
something
end
rescue
something
end
end
endUse :: only to reference constants (this includes classes and modules) and
constructors (like Array() or Nokogiri::HTML()). Avoid :: for
regular method invocation.
Avoid using :: for defining class and modules, or for inheritance, since
constant lookup will not search in parent classes/modules.
# bad
module A
FOO = "test"
end
class A::B
puts FOO # this will raise a NameError exception
end
# good
module A
FOO = "test"
class B
puts FOO
end
endUse def with parentheses when there are parameters. Omit the parentheses when the method doesn't accept any parameters.
Avoid for.
Avoid then.
Favour the ternary operator(?:) over if/then/else/end constructs.
# bad
result = if some_condition then something else something_else end
# good
result = some_condition ? something : something_elseUse one expression per branch in a ternary operator. This also means that ternary operators must not be nested. Prefer if/else constructs in these cases.
Avoid multiline ?: (the ternary operator); use if/unless instead.
Use when x then ... for one-line cases.
Use ! instead of not.
Prefer &&/|| over and/or.
Favour unless over if for negative conditions.
Avoid unless with else. Rewrite these with the positive case first.
Use parentheses around the arguments of method invocations. Omit parentheses when not providing arguments. Also omit parentheses when the invocation is single-line and the method:
1 + 1 calls the + method, foo[bar]
calls the [] method, etc).# bad
class User
include(Bar)
has_many(:posts)
end
# good
class User
include Bar
has_many :posts
SomeClass.some_method(:foo)
endrequirerequire_relativerequire_dependencyyieldraiseputsOmit the outer braces around an implicit options hash.
Use the proc invocation shorthand when the invoked method is the only operation of a block.
# bad
names.map { |name| name.upcase }
# good
names.map(&:upcase)Prefer {...} over do...end for single-line blocks.
Prefer do..end over {...} for multi-line blocks.
Omit return where possible.
Omit self where possible.
# bad
self.my_method
# good
my_method
# also good
attr_writer :name
def my_method
self.name = "Rafael" # `self` is needed to reference the attribute writer.
endWrap assignment in parentheses when using its return value in a conditional statement.
if (value = /foo/.match(string))Use ||= to initialize variables only if they're not already initialized.
Avoid using ||= to initialize boolean variables.
# bad - would set enabled to true even if it was false
@enabled ||= true
# good
@enabled = true if @enabled.nil?
# also valid - defined? workaround
@enabled = true unless defined?(@enabled)Avoid spaces between a method name and the opening parenthesis.
Prefer the lambda literal syntax over lambda.
# bad
l = lambda { |a, b| a + b }
l.call(1, 2)
l = lambda do |a, b|
tmp = a * 7
tmp * b / 50
end
# good
l = ->(a, b) { a + b }
l.call(1, 2)
l = ->(a, b) do
tmp = a * 7
tmp * b / 50
endPrefer proc over Proc.new.
Prefix unused block parameters with _. It's also acceptable to use just _.
Prefer a guard clause when you can assert invalid data. A guard clause is a conditional statement at the top of a function that bails out as soon as it can.
# bad
def compute_thing(thing)
if thing[:foo]
update_with_bar(thing)
if thing[:foo][:bar]
partial_compute(thing)
else
re_compute(thingNo open issues yet, or sync has not completed.