aboutsummaryrefslogtreecommitdiffstats
path: root/activesupport/lib/active_support/core_ext/date/behavior.rb
blob: 50c77867f8f9331a5eed16823209994d107534d5 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
require 'date'

module ActiveSupport #:nodoc:
  module CoreExtensions #:nodoc:
    module Date #:nodoc:
      module Behavior
        # Enable more predictable duck-typing on Date-like classes. See
        # Object#acts_like?.
        def acts_like_date?
          true
        end

        # Date memoizes some instance methods using metaprogramming to wrap
        # the methods with one that caches the result in an instance variable.
        #
        # If a Date is frozen but the memoized method hasn't been called, the
        # first call will result in a frozen object error since the memo
        # instance variable is uninitialized.
        #
        # Work around by eagerly memoizing before freezing.
        #
        # Ruby 1.9 uses a preinitialized instance variable so it's unaffected.
        # This hack is as close as we can get to feature detection:
        if (Date.today.freeze.inspect rescue false)
          def freeze #:nodoc:
            self.class.private_instance_methods(false).each do |m|
              if m.to_s =~ /\A__\d+__\Z/
                instance_variable_set(:"@#{m}", [send(m)])
              end
            end

            super
          end
        end
      end
    end
  end
end