2 # Declare an attribute accessor with an initial default return value.
4 # To give attribute <tt>:age</tt> the initial value <tt>25</tt>:
7 # attr_accessor_with_default :age, 25
12 # some_person.age = 26
16 # To give attribute <tt>:element_name</tt> a dynamic default value, evaluated
19 # attr_accessor_with_default(:element_name) { name.underscore }
21 def attr_accessor_with_default(sym
, default
= nil, &block
)
22 raise 'Default value or block required' unless !default
.nil? || block
23 define_method(sym
, block_given
? ? block
: Proc
.new
{ default
})
24 module_eval(<<-EVAL, __FILE__, __LINE__)
26 class << self; attr_reader :#{sym} end