Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Ruby Style Guide

Ruby/Rails Style Guide

Whitespace

  • Use 2-space indentation (no tabs).
  • Remove trailing whitespace.
  • Use Unix-style line endings.
  • Use spaces around operators, after commas, colons and semicolons, around { and before }.
  • Use two spaces before statement modifiers (e.g. postfix if, unless, while, until, or rescue).
  • Use empty lines to break up a long method into logical paragraphs.
  • Keep lines to fewer than 132 characters.
  • Do not indent temporary or debugging code (e.g. debugger), but keep flush with left column for visibility.
  • Do not indent class access control statements (e.g. protected). That is, they should be aligned with the opening class and closing end lines.

Naming Conventions

  • Method names should start with a lower case letter, and should be in all lower-case: method_name
  • Prefer attr_reader, attr_writer, attr_accessor for simple attributes.
  • Accessor and mutator methods are simply the name of the attribute (without get_ or set_ prefix).
  • Prefer attribute= over set_attribute.
  • Methods that return a boolean should end in ? and do not have the is_ prefix: prefer active? over is_active or is_active.
  • Method names should end in ! if the method:
    • Changes the object directly, as opposed to returning a modified copy of the object.
    • Throws an exception on a failure condition, as opposed to returning nil or false.

Usage Conventions

  • Always use parentheses around arguments in a function definition.
  • Use && and || for boolean expressions, and and or for control flow.
  • Avoid multiline ternary operator ( ?: ), prefer if.
  • Prefer methods over comparisons, e.g.:
  • Prefer unless over if !, except when there are elsif or else clauses.
    • t.empty? instead of t.size == 0
    • t.zero? instead of t == 0

HAML

  • Use single space after = or -
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.