Skip to content

Ruby Style Guide

AnthonySuper edited this page Dec 31, 2014 · 5 revisions

Formatting

Indent with 2 spaces. NEVER USE TABS.

def good
  return true
end

Always add a trailing newline to the end of a file.

Try your best not to go over 80 character line widths.

When nesting multiple blocks, use one end per line:

def good
  example do |x|
    puts x
  end
end

Leave one newline between methods in a class. Add documentation comments for the methods in a class above where they are declared. Do not add newlines between the start of a class and the start of the first method, or the end of the last method and the end of a class.

class Format
  ##
  # Initialize with an example formatter 
  def initialize(formatter)
    @formatter = formatter
    @formatter.test!
  end

  def test(str)
    @formatter.test(str).map do |x|
      x.format!
    end
  end
end

When chaining methods on multiple lines, put the dot before the method, and indent twice:

foo.bar
    .baz
    .test
    .image
    .select{|x| x > 3}

# Always indent twice, even if the method is longer
foo.do_a_thing_with_stuff
    .another
    .even_a_bigger_thing

Conventions, Constructs, and Naming

You should never have to use a for in loop. Use constructs like .each instead.

Prefer transformations like map and select over loops.

Use snake_case for variable and method names, and CamelCase for object names. Constants should be SCREAMING_SNAKE_CASE

When working with blocks, it is okay to name the block elements with one-letter variable names, if the block is less than 3 lines long.

# good
[1,2,3].each do |x|
  print(x)
  store(x)
  dance_with(x)
end

# bad:
[1,2,3].each do |x|
  buy(x)
  use(x)
  break(x)
  fix(x)
  trash(x)
  change(x)
  mail(x)
  upgrade(x)
end

When at all possible, avoid mutating your arguments. Try to code in a semi-functional style.

Rails-Specific

Controllers

Create a helper method for the params of the model the controller deals with. Name it ````"#{model_name}_params". Use protected parameters in this.

Clone this wiki locally