method
attr_accessor_with_default
v2.2.1 -
Show latest stable
-
2 notes -
Class: Module
- 1.0.0
- 1.1.6
- 1.2.6
- 2.0.3
- 2.1.0 (0)
- 2.2.1 (0)
- 2.3.8 (0)
- 3.0.0 (0)
- 3.0.9 (-3)
- 3.1.0 (1)
- 3.2.1
- 3.2.8
- 3.2.13
- 4.0.2
- 4.1.8
- 4.2.1
- 4.2.7
- 4.2.9
- 5.0.0.1
- 5.1.7
- 5.2.3
- 6.0.0
- 6.1.3.1
- 6.1.7.7
- 7.0.0
- 7.1.3.2
- 7.1.3.4
- What's this?
attr_accessor_with_default(sym, default = nil, &block)
public
Declare an attribute accessor with an initial default return value.
To give attribute :age the initial value 25:
class Person attr_accessor_with_default :age, 25 end some_person.age => 25 some_person.age = 26 some_person.age => 26
To give attribute :element_name a dynamic default value, evaluated in scope of self:
attr_accessor_with_default(:element_name) { name.underscore }
Register or
log in
to add new notes.
stevo -
September 13, 2011
1 thank
Some unexpected behaviour
When using Array as default value, it behaves more like cattr_accessor…
class A attr_accessor_with_default :b, [] end x = A.new x.b << 1 #puts x.b.inspect => [1] y = A.new y.b << 2 #puts y.b.inspect => [1, 2]
stevo -
October 10, 2011 - (>= v3.1.0)
1 thank
Use Ruby instead!
E.g.
class TestClass < SomeSuperClass attr_accessor :sample_acc def initialize @sample_acc = [] super end end
If nil is not a valid value for this accessor, then you can just define reader for it.
class TestClass attr_accessor :sample_acc def sample_acc @sample_acc ||= 98 end end