text stringlengths 0 444 |
|---|
If you really need "global" methods, add them to Kernel and make them private. |
== Classes & Modules |
=== Consistent Classes [[consistent-classes]] |
Use a consistent structure in your class definitions. |
[source,ruby] |
---- |
class Person |
# extend/include/prepend go first |
extend SomeModule |
include AnotherModule |
prepend YetAnotherModule |
# inner classes |
class CustomError < StandardError |
end |
# constants are next |
SOME_CONSTANT = 20 |
# afterwards we have attribute macros |
attr_reader :name |
# followed by other macros (if any) |
validates :name |
# public class methods are next in line |
def self.some_method |
end |
# initialization goes between class methods and other instance methods |
def initialize |
end |
# followed by other public instance methods |
def some_method |
end |
# protected and private methods are grouped near the end |
protected |
def some_protected_method |
end |
private |
def some_private_method |
end |
end |
---- |
=== Mixin Grouping [[mixin-grouping]] |
Split multiple mixins into separate statements. |
[source,ruby] |
---- |
# bad |
class Person |
include Foo, Bar |
end |
# good |
class Person |
# multiple mixins go in separate statements |
include Foo |
include Bar |
end |
---- |
=== Single-line Classes [[single-line-classes]] |
Prefer a two-line format for class definitions with no body. It is easiest to read, understand, and modify. |
[source,ruby] |
---- |
# bad |
FooError = Class.new(StandardError) |
# okish |
class FooError < StandardError; end |
# ok |
class FooError < StandardError |
end |
---- |
NOTE: Many editors/tools will fail to understand properly the usage of `Class.new`. |
Someone trying to locate the class definition might try a grep "class FooError". |
A final difference is that the name of your class is not available to the `inherited` |
callback of the base class with the `Class.new` form. |
In general it's better to stick to the basic two-line style. |
=== File Classes [[file-classes]] |
Don't nest multi-line classes within classes. |
Try to have such nested classes each in their own file in a folder named like the containing class. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.