text
stringlengths 0
444
|
|---|
=== Accessor/Mutator Method Names [[accessor_mutator_method_names]]
|
For accessors and mutators, avoid prefixing method names with `get_` and `set_`.
|
It is a Ruby convention to use attribute names for accessors (readers) and `attr_name=` for mutators (writers).
|
[source,ruby]
|
----
|
# bad
|
class Person
|
def get_name
|
"#{@first_name} #{@last_name}"
|
end
|
def set_name(name)
|
@first_name, @last_name = name.split(' ')
|
end
|
end
|
# good
|
class Person
|
def name
|
"#{@first_name} #{@last_name}"
|
end
|
def name=(name)
|
@first_name, @last_name = name.split(' ')
|
end
|
end
|
----
|
=== `attr` [[attr]]
|
Avoid the use of `attr`.
|
Use `attr_reader` and `attr_accessor` instead.
|
[source,ruby]
|
----
|
# bad - creates a single attribute accessor (deprecated in Ruby 1.9)
|
attr :something, true
|
attr :one, :two, :three # behaves as attr_reader
|
# good
|
attr_accessor :something
|
attr_reader :one, :two, :three
|
----
|
=== `Struct.new` [[struct-new]]
|
Consider using `Struct.new`, which defines the trivial accessors, constructor and comparison operators for you.
|
[source,ruby]
|
----
|
# good
|
class Person
|
attr_accessor :first_name, :last_name
|
def initialize(first_name, last_name)
|
@first_name = first_name
|
@last_name = last_name
|
end
|
end
|
# better
|
Person = Struct.new(:first_name, :last_name) do
|
end
|
----
|
=== Don't Extend `Struct.new` [[no-extend-struct-new]]
|
Don't extend an instance initialized by `Struct.new`.
|
Extending it introduces a superfluous class level and may also introduce weird errors if the file is required multiple times.
|
[source,ruby]
|
----
|
# bad
|
class Person < Struct.new(:first_name, :last_name)
|
end
|
# good
|
Person = Struct.new(:first_name, :last_name)
|
----
|
=== Don't Extend `Data.define` [[no-extend-data-define]]
|
Don't extend an instance initialized by `Data.define`.
|
Extending it introduces a superfluous class level.
|
[source,ruby]
|
----
|
# bad
|
class Person < Data.define(:first_name, :last_name)
|
end
|
Person.ancestors
|
# => [Person, #<Class:0x0000000105abed88>, Data, Object, (...)]
|
# good
|
Person = Data.define(:first_name, :last_name)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.