Classes
Avoid the usage of class (
@@
) variables
due to their “nasty” behavior in inheritance.
[link]class Parent
@@class_var = 'parent'
def self.print_class_var
puts @@class_var
end
end
class Child < Parent
@@class_var = 'child'
end
Parent.print_class_var # => will print "child"
As you can see all the classes in a class hierarchy actually share one
class variable. Class instance variables should usually be preferred
over class variables.Use
def self.method
to define singleton
methods. This makes the methods more resistant to refactoring changes.
[link]class TestClass
# bad
def TestClass.some_method
...
end
# good
def self.some_other_method
...
end
Avoid
class << self
except when necessary,
e.g. single accessors and aliased attributes.
[link]class TestClass
# bad
class << self
def first_method
...
end
def second_method_etc
...
end
end
# good
class << self
attr_accessor :per_page
alias_method :nwo, :find_by_name_with_owner
end
def self.first_method
...
end
def self.second_method_etc
...
end
end
Indent the
public
,protected
, and
private
methods as much the method definitions they apply to. Leave one
blank line above and below them.[link]class SomeClass
def public_method
# ...
end
private
def private_method
# ...
end
end