text
stringlengths 0
444
|
|---|
[source,ruby]
|
----
|
# bad
|
# foo.rb
|
class Foo
|
class Bar
|
# 30 methods inside
|
end
|
class Car
|
# 20 methods inside
|
end
|
# 30 methods inside
|
end
|
# good
|
# foo.rb
|
class Foo
|
# 30 methods inside
|
end
|
# foo/bar.rb
|
class Foo
|
class Bar
|
# 30 methods inside
|
end
|
end
|
# foo/car.rb
|
class Foo
|
class Car
|
# 20 methods inside
|
end
|
end
|
----
|
=== Namespace Definition [[namespace-definition]]
|
Define (and reopen) namespaced classes and modules using explicit nesting.
|
Using the scope resolution operator can lead to surprising constant lookups due to Ruby's https://cirw.in/blog/constant-lookup.html[lexical scoping], which depends on the module nesting at the point of definition.
|
[source,ruby]
|
----
|
module Utilities
|
class Queue
|
end
|
end
|
# bad
|
class Utilities::Store
|
Module.nesting # => [Utilities::Store]
|
def initialize
|
# Refers to the top level ::Queue class because Utilities isn't in the
|
# current nesting chain.
|
@queue = Queue.new
|
end
|
end
|
# good
|
module Utilities
|
class WaitingList
|
Module.nesting # => [Utilities::WaitingList, Utilities]
|
def initialize
|
@queue = Queue.new # Refers to Utilities::Queue
|
end
|
end
|
end
|
----
|
=== Modules vs Classes [[modules-vs-classes]]
|
Prefer modules to classes with only class methods.
|
Classes should be used only when it makes sense to create instances out of them.
|
[source,ruby]
|
----
|
# bad
|
class SomeClass
|
def self.some_method
|
# body omitted
|
end
|
def self.some_other_method
|
# body omitted
|
end
|
end
|
# good
|
module SomeModule
|
module_function
|
def some_method
|
# body omitted
|
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.