Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@M0119
Last active March 23, 2019 03:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save M0119/be1b54cb9471ed4854e9a408b395d174 to your computer and use it in GitHub Desktop.
Save M0119/be1b54cb9471ed4854e9a408b395d174 to your computer and use it in GitHub Desktop.

Lecture ✍️

This is M0119's ruby terminal app style guide.

It was inspired by Airbnb's guide.

Table of Contents

  1. Whitespace
    1. Indentation
    2. Inline
    3. Newlines
  2. Line Length
  3. Commenting
  4. Methods
    1. Method definitions
    2. Method calls
  5. Collections
  6. Be Consistent

Whitespace

Indentation

  • Use a four-space indent (Visual Studio default).

    if song.name == 'Misty'
      puts 'Not again!'
    elsif song.duration > 120
      puts 'Too long!'
    elsif Time.now.hour > 21
      puts "It's too late"
    else
      song.play
    end
  • Align function parameters either all on the same line or one per line.

    # bad
    def self.create_translation(phrase_id, phrase_key, target_locale,
                                value, user_id, do_xss_check, allow_verification)
      ...
    end
    
    # good
    def self.create_translation(phrase_id,
                                phrase_key,
                                target_locale,
                                value,
                                user_id,
                                do_xss_check,
                                allow_verification)
      ...
    end
    
    # good
    def self.create_translation(
      phrase_id,
      phrase_key,
      target_locale,
      value,
      user_id,
      do_xss_check,
      allow_verification
    )
      ...
    end

Inline

  • Never leave trailing whitespace.

  • Use spaces around operators; after commas, colons, and semicolons; and around { and before }.

    sum = 1 + 2
    [1, 2, 3].each { |e| puts e }
  • Never include a space before a comma.

    result = func(a, b)
  • Do not include space inside block parameter pipes. Include one space between parameters in a block. Include one space outside block parameter pipes.

    # bad
    {}.each { | x,  y |puts x }
    
    # good
    {}.each { |x, y| puts x }
  • Do not leave space between ! and its argument.

    !something
  • No spaces after (, [ or before ], ).

    some(arg).other()
    [1, 2, 3].length()
  • Omit whitespace when doing string interpolation.

    # bad
    var = "This #{ foobar } is interpolated."
    
    # good
    var = "This #{foobar} is interpolated."
  • Don't use extra whitespace in range literals.

    # bad
    (0 ... coll).each do |item|
    
    # good
    (0...coll).each do |item|

Newlines

  • Add a new line after if conditions spanning multiple lines to help differentiate between the conditions and the body.

    if (reservation_alteration.checkin == reservation.start_date &&
       reservation_alteration.checkout == (reservation.start_date + reservation.nights))
    
      redirect_to_alteration(reservation_alteration)
    end
  • Add a new line after conditionals, blocks, case statements, etc.

    if robot.is_awesome?()
      send_robot_present()
    end
    
    robot.add_trait(:human_like_intelligence)
  • Don’t include newlines between areas of different indentation (such as around class or module bodies).

    # bad
    class Foo
    
      def bar
        # body omitted
      end
    
    end
    
    # good
    class Foo
      def bar
        # body omitted
      end
    end
  • Include one, but no more than one, new line between methods.

    def fizz()
    end
    
    def buzz()
    end
  • Use a single empty line to break between statements to break up methods into logical paragraphs internally.

    def transformorize_car()
      car = manufacture(options)
      t = transformer(robot, disguise)
    
      car.after_market_mod!
      t.transform(car)
      car.assign_cool_name!
    
      fleet.add(car)
      car
    end
  • End each file with a newline. Don't include multiple newlines at the end of a file.

Line Length

  • Keep each line of code to a readable length. Unless you have a reason to, keep lines to fewer than 100 characters.

Naming

  • Use CamelCase for classes and modules. (Keep acronyms like HTTP, RFC, XML uppercase.)

  • Use SCREAMING_SNAKE_CASE for other constants.

  • The names of predicate methods (methods that return a boolean value) should end in a question mark. (i.e. Array#empty?).

  • The names of potentially "dangerous" methods (i.e. methods that modify self or the arguments, exit!, etc.) should end with an exclamation mark. Bang methods should only exist if a non-bang method exists.

  • Name throway variables.

    height = 3  
    width = 4  
    area = height * width   

Commenting

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][google-c++]

# bad
a = h * w  # calculate width

# good
height = 3  
width = 4  
area = height * width 

Comment 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.

Do not use block comments. They cannot be preceded by whitespace and are not as easy to spot as regular comments.

# bad
=begin
comment line
another comment line
=end

# good
# comment line
# another comment line

Methods

Method definitions

  • Always use def with parentheses, when there are parameters and when the method doesn't accept any parameters.

    def some_method()
      # body omitted
    end
    
    def some_method_with_parameters(arg1, arg2)
      # body omitted
    end

Method calls

  • Use parentheses on a method call

    # bad
    current_user = User.find_by_id 1964192
    
    # good
    current_user = User.find_by_id(1964192)
  • Never put a space between a method name and the opening parenthesis.

    # bad
    foo (3 + 2) + 1
    
    # good
    foo(3 + 2) + 1

Collections

  • Use symbols instead of strings as hash keys.

    # bad
    hash = { 
      'one': 1, 
      'two': 2, 
      'three': 3 
      }
    
    # good
    hash = { 
      one: 1, 
      two: 2, 
      three: 3 
      }

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment