Froze rails gems
[depot.git] / vendor / rails / activesupport / lib / active_support / core_ext / module / attr_accessor_with_default.rb
1 class Module
2 # Declare an attribute accessor with an initial default return value.
3 #
4 # To give attribute <tt>:age</tt> the initial value <tt>25</tt>:
5 #
6 # class Person
7 # attr_accessor_with_default :age, 25
8 # end
9 #
10 # some_person.age
11 # => 25
12 # some_person.age = 26
13 # some_person.age
14 # => 26
15 #
16 # To give attribute <tt>:element_name</tt> a dynamic default value, evaluated
17 # in scope of self:
18 #
19 # attr_accessor_with_default(:element_name) { name.underscore }
20 #
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__)
25 def #{sym}=(value)
26 class << self; attr_reader :#{sym} end
27 @#{sym} = value
28 end
29 EVAL
30 end
31 end