Skip to content

Instantly share code, notes, and snippets.

@bricker
Last active December 26, 2015 03:49
Show Gist options
  • Save bricker/7088945 to your computer and use it in GitHub Desktop.
Save bricker/7088945 to your computer and use it in GitHub Desktop.

KPCC Ruby Style Guide

We base our Ruby style off of https://github.com/bbatsov/ruby-style-guide . There are a few other things, which are documented here.

Methods

  • Prefer a short-circuit return to a deeply-nested if condition:
# good
PREFIX = "Article:"

def long_title
  return nil if !@title

  "#{PREFIX} #{@title}"
end

# bad
def long_title
  if @title
    "#{PREFIX} #{@title}"
  end
end
  • Try not to put literals into methods. Instead, define constants at the top of the class and reference those in the method:
class Article
  API_ROOT = "http://scpr.org/api/v2/"
  PATH     = "articles"

  LIMIT     = 10
  DIRECTION = "DESC"
  
  class << self
    def all
      fetch(endpoint, LIMIT, DIRECTION)
    end

    def endpoint
      API_ROOT + PATH
    end
  end
end
  • Prefer class << self over self.some_method for class methods.

If/Else

  • We don't generally use post-IF syntax, unless it's something very short.

Hashes

  • Either 1.8 syntax ({ :hash => "rockets" }) or 1.9 syntax ({ javascript: "style"}) are okay.
  • For hashes with more than 1 key, use hash rockets across multiple lines (1 key/value per line).
  • Line up the rockets:
short_hash = { title: "Hash" }

long_hash  = {
  :title     => "Hash",
  :purpose   => "Style Guide",
  :type      => "Example"
}
  • 1.9 syntax should be used only for 1-key hashes usually. Use your discretion.
  • Space between { ... } and the key/values:
# good
hash = { title: "Hash" }

# bad
hash = {title: "hash"}

Lambdas/Procs

  • Use the 1.9 syntax for Lambdas:
upcase = ->(str) { str.upcase }
  • Use the proc keyword (instead of Proc.new) for Procs:
upcase = proc { |str| str.upcase }

Line Lengths

  • Lines should not exceed 80 characters in length.
  • Break up long strings with a backslash:
some_long_string =  "This string is really long, but it's okay, " \
                    "because we're going to break it up over two lines."
  • attr_* in classes should be broken up over multiple lines, one symbol per line:
# good
attr_accessor \
  :title,
  :type,
  :purpose

# bad
attr_accessor :title, :type, :purpose

White Space

  • Do not leave any trailing white space, except where it needs to be present. The only thing I know of that actually uses trailing white space is Markdown.
  • Every file should have an empty newline at the bottom.
  • Blank lines should not be indented at all.
  • A regular expression file search for +\n should return no results.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment