Good practices for having readable code
Nathaly Villamor
is a programming language
is objected-oriented
powerful string operations and regular expressions
quick and easy
class Foo
def self::some_method
end
end
class Foo
def self.some_method
end
end
def some_method()
# body omitted
end
def some_method
# body omitted
end
def some_method_with_parameters param1, param2
# body omitted
end
def some_method_with_parameters(param1, param2)
# body omitted
end
attr_reader(:name, :age)
attr_reader :name, :age
a, b, c, d = 'foo', 'bar', 'baz', 'foobar'
a = 'foo'
b = 'bar'
c = 'baz'
d = 'foobar'
for elem in arr do
puts elem
end
arr.each { |elem| puts elem }
class HomeController < ApplicationController
def index
# bad
@recent_books = Book.where("books.published_at > ?", 1.week.ago).order("books.published_at DESC")
end
end
class HomeController < ApplicationController
def index
# good
@recent_books = Book.recent.published_desc
# 'recent' and 'published_desc' are scopes defined in Book model
end
end
Rails
#bad
def search
params.except!(:action, :controller)
@search = User.search(params)
render "search"
end
# better
def search
@search = User.search(search_params)
render "search"
end
private
def search_params
# params.except(:action, :controller)
params.permit(:user_id, :name)
end
Rails
#bad
begin
foo
rescue Exception => e
logger.warn "Unable to foo, will ignore: #{e}"
end
#good
begin
foo
rescue => e
logger.warn "Unable to foo, will ignore: #{e}"
end
# also good
begin
# an exception occurs here
rescue StandardError => e
logger.warn "Unable to foo, will ignore: #{e}"
end
def foo
begin
# main logic goes here
rescue
# failure handling goes here
end
end
def foo
# main logic goes here
rescue
# failure handling goes here
end
{ a: 1, 'b' => 2 }
{ :a => 1, 'b' => 2 }
hash.key?(:test)
hash.value?(value)
hash.has_key?(:test)
hash.has_value?(value)
[*paths].each { |path| do_something(path) }
paths = [paths] unless paths.is_a? Array
paths.each { |path| do_something(path) }
Array(paths).each { |path| do_something(path) }
unless !holi
#do something
end
if holi.present?
#do something
end
Rails