liftopia / ruby-styleguide

0 stars 0 forks source link

Ruby Style Guide

These are standards and conventions we use for Ruby code at Airbnb. Please take what is useful to you.

We based our Ruby style on the excellent Github Ruby Styleguide, which in turn was inspired by Bozhidar Batsov's guide.

We also maintain a JavaScript Style Guide.

Table of Contents

  1. Whitespace
    1. Indentation
    2. Inline
    3. Newlines
  2. Line Length
  3. Commenting
    1. File/class-level comments
    2. Function comments
    3. Block and inline comments
    4. Punctuation, spelling, and grammar
    5. TODO comments
    6. Commented-out code
  4. Methods
    1. Method definitions
    2. Method calls
  5. Conditional Expressions
    1. Conditional keywords
    2. Ternary operator
  6. Syntax
  7. Naming
  8. Classes
  9. Exceptions
  10. Collections
  11. Strings
  12. Regular Expressions
  13. Percent Literals
  14. Rails Specific
  15. Be Consistent

Whitespace

Indentation

Inline

Newlines

Line Length

Keep each line of code to a readable length. Unless you have a reason to, keep lines to fewer than 100 characters. Keeping code visually grouped together (as a 100-character line limit enforces) makes it easier to understand. For example, you don't have to scroll back and forth on one line to see what's going on -- you can view it all together.

Here are examples from our codebase showing several techniques for breaking complex statements into multiple lines that are all < 100 characters. Notice techniques like:

scope = Translation::Phrase.includes(:phrase_translations).
  joins(:phrase_screenshots).
  where(phrase_screenshots: {
    controller: controller_name,
    action: JAROMIR_JAGR_SALUTE,
  })
translation = FactoryGirl.create(
  :phrase_translation,
  locale: :is,
  phrase: phrase,
  key: 'phone_number_not_revealed_time_zone',
  value: 'Símanúmerið þitt verður ekki birt. Það er aðeins hægt að hringja á '\
            'milli 9:00 og 21:00 %{time_zone}.'
)
if @reservation_alteration.checkin == @reservation.start_date &&
   @reservation_alteration.checkout == (@reservation.start_date + @reservation.nights)

  redirect_to_alteration @reservation_alteration
end
<% if @presenter.guest_visa_russia? %>
  <%= icon_tile_for(I18n.t("email.reservation_confirmed_guest.visa.details_header",
                           default: "Visa for foreign Travelers"),
                    beveled_big_icon: "stamp" do %>
    <%= I18n.t("email.reservation_confirmed_guest.visa.russia.details_copy",
               default: "Foreign guests travelling to Russia may need to obtain a visa...") %>
  <% end %>
<% end %>

These code snippets are very much more readable than the alternative:

scope = Translation::Phrase.includes(:phrase_translations).joins(:phrase_screenshots).where(phrase_screenshots: { controller: controller_name, action: JAROMIR_JAGR_SALUTE })

translation = FactoryGirl.create(:phrase_translation, locale: :is, phrase: phrase, key: 'phone_number_not_revealed_time_zone', value: 'Símanúmerið þitt verður ekki birt. Það er aðeins hægt að hringja á milli 9:00 og 21:00 %{time_zone}.')

if @reservation_alteration.checkin == @reservation.start_date && @reservation_alteration.checkout == (@reservation.start_date + @reservation.nights)
  redirect_to_alteration @reservation_alteration
end
<% if @presenter.guest_visa_russia? %>
  <%= icon_tile_for(I18n.t("email.reservation_confirmed_guest.visa.details_header", default: "Visa for foreign Travelers"), beveled_big_icon: "stamp" do %>
    <%= I18n.t("email.reservation_confirmed_guest.visa.russia.details_copy", default: "Foreign guests travelling to Russia may need to obtain a visa prior to...") %>
  <% end %>
<% end %>

Commenting

Though a pain to write, comments are absolutely vital to keeping our code readable. The following rules describe what you should comment and where. But remember: while comments are very important, the best code is self-documenting. Giving sensible names to types and variables is much better than using obscure names that you must then explain through comments.

When writing your comments, write for your audience: the next contributor who will need to understand your code. Be generous — the next one may be you!

Google C++ Style Guide

Portions of this section borrow heavily from the Google C++ and Python style guides.

File/class-level comments

Every class definition should have an accompanying comment that describes what it is for and how it should be used.

A file that contains zero classes or more than one class should have a comment at the top describing its contents.

# Automatic conversion of one locale to another where it is possible, like
# American to British English.
module Translation
  # Class for converting between text between similar locales.
  # Right now only conversion between American English -> British, Canadian,
  # Australian, New Zealand variations is provided.
  class PrimAndProper
    def initialize
      @converters = { en: { "en-AU": AmericanToAustralian.new,
                               "en-CA": AmericanToCanadian.new,
                               "en-GB": AmericanToBritish.new,
                               "en-NZ": AmericanToKiwi.new,
                             } }
    end

  ...

  # Applies transforms to American English that are common to
  # variants of all other English colonies.
  class AmericanToColonial
    ...
  end

  # Converts American to British English.
  # In addition to general Colonial English variations, changes "apartment"
  # to "flat".
  class AmericanToBritish < AmericanToColonial
    ...
  end

All files, including data and config files, should have file-level comments. From translation/config/colonial_spelling_variants.yml:

# List of American-to-British spelling variants.
#
# This list is made with
# lib/tasks/list_american_to_british_spelling_variants.rake.
#
# It contains words with general spelling variation patterns:
#   [trave]led/lled, [real]ize/ise, [flav]or/our, [cent]er/re, plus
# and these extras:
#   learned/learnt, practices/practises, airplane/aeroplane, ...

sectarianizes: sectarianises
neutralization: neutralisation
...

Function comments

Every function declaration should have comments immediately preceding it that describe what the function does and how to use it. These comments should be descriptive ("Opens the file") rather than imperative ("Open the file"); the comment describes the function, it does not tell the function what to do. In general, these comments do not describe how the function performs its task. Instead, that should be left to comments interspersed in the function's code.

Every function should mention what the inputs and outputs are, unless it meets all of the following criteria:

In Ruby, two popular function documentation schemes are TomDoc and YARD. You should favor using YARD over TomDoc. TomDoc is allowable since there are existing modules using it, but all new documentation should use YARD format.

Block and inline comments

The final place to have comments is in tricky parts of the code. If you're going to have to explain it at the next code review, you should comment it now. Complicated operations get a few lines of comments before the operations commence. Non-obvious ones get comments at the end of the line.

def fallbacks_for(the_locale, opts = {})
  # dup() to produce an array that we can mutate.
  ret = @fallbacks[the_locale].dup

  # We make two assumptions here:
  # 1) There is only one default locale (that is, it has no less-specific
  #    children).
  # 1) The default locale is just a language. (Like :en, and not :"en-US".)
  if opts[:exclude_default] &&
      ret.last == self.default_locale &&
      ret.last != language_from_locale(the_locale)
    ret.pop
  end

  ret
end

On the other hand, never describe the code. Assume the person reading the code knows the language (though not what you're trying to do) better than you do.

Punctuation, spelling and grammar

Pay attention to punctuation, spelling, and grammar; it is easier to read well-written comments than badly written ones.

Comments should be as readable as narrative text, with proper capitalization and punctuation. In many cases, complete sentences are more readable than sentence fragments. Shorter comments, such as comments at the end of a line of code, can sometimes be less formal, but you should be consistent with your style.

Although it can be frustrating to have a code reviewer point out that you are using a comma when you should be using a semicolon, it is very important that source code maintain a high level of clarity and readability. Proper punctuation, spelling, and grammar help with that goal.

TODO comments

Use TODO comments for code that is temporary, a short-term solution, or good-enough but not perfect.

TODOs should include the string TODO in all caps, followed by the full name of the person who can best provide context about the problem referenced by the TODO, in parentheses. A colon is optional. A comment explaining what there is to do is required. The main purpose is to have a consistent TODO format that can be searched to find the person who can provide more details upon request. A TODO is not a commitment that the person referenced will fix the problem. Thus when you create a TODO, it is almost always your name that is given.

  # bad
  # TODO(RS): Use proper namespacing for this constant.

  # bad
  # TODO(drumm3rz4lyfe): Use proper namespacing for this constant.

  # good
  # TODO(Ringo Starr): Use proper namespacing for this constant.

Commented-out code

Never leave commented-out code in our codebase.

Methods

Method definitions

Method calls

Use parentheses for a method call:

Omit parentheses for a method call:

In either case:

Conditional Expressions

Conditional keywords

Ternary operator

Syntax

Naming

Classes

Exceptions

Collections

Regular Expressions

Percent Literals

Rails

Be Consistent

If you're editing code, take a few minutes to look at the code around you and determine its style. If they use spaces around all their arithmetic operators, you should too. If their comments have little boxes of hash marks around them, make your comments have little boxes of hash marks around them too.

The point of having style guidelines is to have a common vocabulary of coding so people can concentrate on what you're saying rather than on how you're saying it. We present global style rules here so people know the vocabulary, but local style is also important. If code you add to a file looks drastically different from the existing code around it, it throws readers out of their rhythm when they go to read it. Avoid this.

Google C++ Style Guide