Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
R

ruby-style-guide

> 开发工具
Open source

Shopify’s Ruby Style Guide

630 stars0 likes2 views
WebsiteGitHub

About

Shopify’s Ruby Style Guide


layout: default title: Ruby Style Guide permalink: '/'

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.

Adoption with RuboCop

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:

ruby
gem "rubocop-shopify", require: false

And add to the top of your project's RuboCop configuration file:

yaml
inherit_gem:
  rubocop-shopify: rubocop.yml

Any 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.

Table of Contents

  • General
  • Layout
  • Syntax
  • Naming
  • Classes and Modules
  • Exceptions
  • Collections
  • Strings
  • Regular Expressions
  • Percent Literals
  • Testing

General

  • 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.

  • Avoid defensive programming

    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.

Layout

  • 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.

    ruby
    # bad
    foo . bar
    
    # good
    foo.bar
  • Avoid space in lambda literals.

    ruby
    # 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.

    ruby
    # bad
    result =
      if some_cond
        # ...
        # ...
        calc_something
      else
        calc_something_else
      end
    
    # good
    result = if some_cond
      # ...
      # ...
      calc_something
    else
      calc_something_else
    end
  • When assigning the result of a begin block, align rescue/ensure/end with the start of the line

    ruby
    # bad
    host = begin
             URI.parse(value).host
           rescue URI::Error
             nil
           end
    
    # good
    host = begin
      URI.parse(value).host
    rescue URI::Error
      nil
    end
  • Use 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.

    ruby
    # 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,
      )
    end
  • When chaining methods on multiple lines, indent successive calls by one level of indentation.

    ruby
    # 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:

    ruby
    # bad
    =begin
    comment line
    another comment line
    =end
    
    # good
    # comment line
    # another comment line
  • Place the closing method call brace on the line after the last argument when opening brace is on a separate line from the first argument.

    ruby
    # 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.

    ruby
    # 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.

    ruby
    # 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
    end
  • Use empty lines around attribute accessor.

    ruby
    # bad
    class Foo
      attr_reader :foo
      def foo
        # do something...
      end
    end
    
    # good
    class Foo
      attr_reader :foo
    
      def foo
        # do something...
      end
    end
  • Avoid empty lines around method, class, module, and block bodies.

    ruby
    # 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
    end

Syntax

  • Use :: 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.

    ruby
    # 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
    end
  • Use 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.

    ruby
    # bad
    result = if some_condition then something else something_else end
    
    # good
    result = some_condition ? something : something_else
  • Use 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:

    • is a class method call with implicit receiver.
    • is called by syntactic sugar (e.g: 1 + 1 calls the + method, foo[bar] calls the [] method, etc).
    ruby
    # bad
    class User
      include(Bar)
      has_many(:posts)
    end
    
    # good
    class User
      include Bar
      has_many :posts
      SomeClass.some_method(:foo)
    end
    • is one of the following methods:
      • require
      • require_relative
      • require_dependency
      • yield
      • raise
      • puts
  • Omit the outer braces around an implicit options hash.

  • Use the proc invocation shorthand when the invoked method is the only operation of a block.

    ruby
    # 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.

    ruby
    # 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.
    end
  • Wrap assignment in parentheses when using its return value in a conditional statement.

    ruby
    if (value = /foo/.match(string))
  • Use ||= to initialize variables only if they're not already initialized.

  • Avoid using ||= to initialize boolean variables.

    ruby
    # 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.

    ruby
    # 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
    end
  • Prefer 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.

    ruby
    # bad
    def compute_thing(thing)
      if thing[:foo]
        update_with_bar(thing)
        if thing[:foo][:bar]
          partial_compute(thing)
        else
          re_compute(thing

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

Rubyrubocoprubystyle-guide

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category开发工具
PricingOpen source

> Related tools

V
VS Code
流行的开源代码编辑器
G
Git
分布式版本控制系统
V
Vite
下一代前端构建工具