Feature #8564

Extend Module#attr... methods

Added by Boris Stitnicky 10 months ago. Updated 10 months ago.

[ruby-core:55623]
Status:Open
Priority:Normal
Assignee:-
Category:-
Target version:-

Description

Extend #attrreader, #attrwriter, #attr_accessor syntax to accept default values, such as:

attr_reader foo: 42, bar: 43

Possibility of closures evaluated at initialization time might also be considered:

attr_reader baz: -> { Time.now }, quux: 42

History

#1 Updated by Matthew Kerwin 10 months ago

+1 very useful pattern

#2 Updated by Charlie Somerville 10 months ago

-1 to overloading the same syntax with proc/lambda initialization.

#3 Updated by Yukihiro Matsumoto 10 months ago

We need to clarify how this intervene with #initialize. Any opinion?

Matz

#4 Updated by Matthew Kerwin 10 months ago

=begin
matz (Yukihiro Matsumoto) wrote:

We need to clarify how this intervene with #initialize. Any opinion?

Matz

My suggestion is that it take effect before any explicit initialize method.

Examples:

class A
attr_accessor foo: 3
def initialize
p @foo if defined? @foo
@foo = 4
end
end
p A.new.foo #=> prints 3, then 4

class B0
attr_accessor foo: 3
end
class B1 < B0
def initialize
p @foo if defined? @foo
@foo = 4
end
end
p B1.new.foo #=> prints 3, then 4

class C0
def initialize
p @foo if defined? @foo
@foo = 4
end
end
class C1 < C0
attr_accessor foo: 3
end
p C1.new.foo #=> prints 3, then 4
=end

Also available in: Atom PDF