method

attr_accessor_with_default

rails latest stable - Class: Module

Method deprecated or moved

This method is deprecated or moved on the latest stable version. The last existing version (v3.1.0) is shown here.

attr_accessor_with_default(sym, default = Proc.new)
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

person = Person.new
person.age # => 25

person.age = 26
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 }

2Notes

Some unexpected behaviour

stevo · Sep 13, 20111 thank

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]

Use Ruby instead!

stevo · Oct 10, 20111 thank

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