text
stringlengths 0
444
|
|---|
Use `def self.method` to define class methods.
|
This makes the code easier to refactor since the class name is not repeated.
|
[source,ruby]
|
----
|
class TestClass
|
# bad
|
def TestClass.some_method
|
# body omitted
|
end
|
# good
|
def self.some_other_method
|
# body omitted
|
end
|
# Also possible and convenient when you
|
# have to define many class methods.
|
class << self
|
def first_method
|
# body omitted
|
end
|
def second_method_etc
|
# body omitted
|
end
|
end
|
end
|
----
|
=== Alias Method Lexically [[alias-method-lexically]]
|
Prefer `alias` when aliasing methods in lexical class scope as the resolution of `self` in this context is also lexical, and it communicates clearly to the user that the indirection of your alias will not be altered at runtime or by any subclass unless made explicit.
|
[source,ruby]
|
----
|
class Westerner
|
def first_name
|
@names.first
|
end
|
alias given_name first_name
|
end
|
----
|
Since `alias`, like `def`, is a keyword, prefer bareword arguments over symbols or strings.
|
In other words, do `alias foo bar`, not `alias :foo :bar`.
|
Also be aware of how Ruby handles aliases and inheritance: an alias references the method that was resolved at the time the alias was defined; it is not dispatched dynamically.
|
[source,ruby]
|
----
|
class Fugitive < Westerner
|
def first_name
|
'Nobody'
|
end
|
end
|
----
|
In this example, `Fugitive#given_name` would still call the original `Westerner#first_name` method, not `Fugitive#first_name`.
|
To override the behavior of `Fugitive#given_name` as well, you'd have to redefine it in the derived class.
|
[source,ruby]
|
----
|
class Fugitive < Westerner
|
def first_name
|
'Nobody'
|
end
|
alias given_name first_name
|
end
|
----
|
=== `alias_method` [[alias-method]]
|
Always use `alias_method` when aliasing methods of modules, classes, or singleton classes at runtime, as the lexical scope of `alias` leads to unpredictability in these cases.
|
[source,ruby]
|
----
|
module Mononymous
|
def self.included(other)
|
other.class_eval { alias_method :full_name, :given_name }
|
end
|
end
|
class Sting < Westerner
|
include Mononymous
|
end
|
----
|
=== Class and `self` [[class-and-self]]
|
When class (or module) methods call other such methods, omit the use of a leading `self` or own name followed by a `.` when calling other such methods.
|
This is often seen in "service classes" or other similar concepts where a class is treated as though it were a function.
|
This convention tends to reduce repetitive boilerplate in such classes.
|
[source,ruby]
|
----
|
class TestClass
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.