~michaelforrest/use-case-mapper/trunk

« back to all changes in this revision

Viewing changes to vendor/rails/activesupport/lib/active_support/core_ext/module/attr_accessor_with_default.rb

  • Committer: Michael Forrest
  • Date: 2010-10-15 16:28:50 UTC
  • Revision ID: michael.forrest@canonical.com-20101015162850-tj2vchanv0kr0dun
refrozeĀ gems

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
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)                        # def age=(value)
 
26
        class << self; attr_reader :#{sym} end  #   class << self; attr_reader :age end
 
27
        @#{sym} = value                         #   @age = value
 
28
      end                                       # end
 
29
    EVAL
 
30
  end
 
31
end