Skip to content

Style Guide: Ruby

Matt Budz edited this page Mar 2, 2023 · 1 revision

Review GitHub's own Styleguide for Ruby, its a great place to start:

https://github.com/styleguide/ruby

This is a small summary:

  • Use soft-tabs with a two space indent.

  • Keep lines fewer than 80 characters.

  • Never leave trailing whitespace.

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

sum = 1 + 2
a, b = 1, 2
1 > 2 ? true : false; puts "Hi"
[1, 2, 3].each { |e| puts e }
  • No spaces after (, [ or before ], ).
some(arg).other
[1, 2, 3].length
  • Indent when as deep as case.
case
when song.name == "Misty"
  puts "Not again!"
when song.duration > 120
  puts "Too long!"
when Time.now.hour > 21
  puts "It's too late"
else
  song.play
end

kind = case year
       when 1850..1889 then "Blues"
       when 1890..1909 then "Ragtime"
       when 1910..1929 then "New Orleans Jazz"
       when 1930..1939 then "Swing"
       when 1940..1950 then "Bebop"
       else "Jazz"
       end

Use empty lines between defs and to break up a method into logical paragraphs.

def some_method
  data = initialize(options)

  data.manipulate!

  data.result
end

def some_method
  result
end

Do not add extra spacing just to align assignments/arguments across multiple lines:

# bad
ActionMailer::Base.default_options          = config['default_options'].symbolize_keys
ActionMailer::Base.default_url_options      = config['default_url_options'].symbolize_keys
ActionMailer::Base.deliver_later_queue_name = :dradis_mailers
ActionMailer::Base.smtp_settings            = config['smtp_settings'].symbolize_keys

# good
ActionMailer::Base.default_options = config['default_options'].symbolize_keys
ActionMailer::Base.default_url_options = config['default_url_options'].symbolize_keys
ActionMailer::Base.deliver_later_queue_name = :dradis_mailers
ActionMailer::Base.smtp_settings = config['smtp_settings'].symbolize_keys

# bad
importer = plugin::Importer.new(
  default_user_id:  default_user_id,
  logger:           logger,
  plugin:           plugin,
  project_id:       project_id
)

# good
importer = plugin::Importer.new(
  default_user_id: default_user_id,
  logger: logger,
  plugin: plugin,
  project_id: project_id
)

Specs

  • Do not use "should" in you your spec description:
it "requires a filename" do

instead of

it "should require a filename" do
  • No controller, view or helper specs
  • Stick to request specs for the time being
Clone this wiki locally