We base our Ruby style off of https://github.com/bbatsov/ruby-style-guide . There are a few other things, which are documented here.
- Prefer a short-circuit
return
to a deeply-nestedif
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
overself.some_method
for class methods.
- We don't generally use post-IF syntax, unless it's something very short.
- 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"}
- Use the 1.9 syntax for Lambdas:
upcase = ->(str) { str.upcase }
- Use the
proc
keyword (instead ofProc.new
) for Procs:
upcase = proc { |str| str.upcase }
- 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
- 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.