deprecation.rb 4.5 KB
Newer Older
1 2
require 'yaml'

3 4
module ActiveSupport
  module Deprecation
5 6 7
    mattr_accessor :debug
    self.debug = false

8 9 10
    # Choose the default warn behavior according to RAILS_ENV.
    # Ignore deprecation warnings in production.
    DEFAULT_BEHAVIORS = {
11 12 13 14 15 16 17 18
      'test'        => Proc.new { |message, callstack|
                         $stderr.puts(message)
                         $stderr.puts callstack.join("\n  ") if debug
                       },
      'development' => Proc.new { |message, callstack|
                         RAILS_DEFAULT_LOGGER.warn message
                         RAILS_DEFAULT_LOGGER.debug callstack.join("\n  ") if debug
                       }
19 20
    }

21
    class << self
22
      def warn(message = nil, callstack = caller)
23
        behavior.call(deprecation_message(callstack, message), callstack) if behavior && !silenced?
24
      end
25

26
      def default_behavior
27 28 29 30 31
        if defined?(RAILS_ENV)
          DEFAULT_BEHAVIORS[RAILS_ENV.to_s]
        else
          DEFAULT_BEHAVIORS['test']
        end
32
      end
33

34 35
      # Have deprecations been silenced?
      def silenced?
36
        @silenced = false unless defined?(@silenced)
37 38 39 40 41 42 43 44 45 46 47 48
        @silenced
      end

      # Silence deprecations for the duration of the provided block. For internal
      # use only.
      def silence
        old_silenced, @silenced = @silenced, true # We could have done behavior = nil...
        yield
      ensure
        @silenced = old_silenced
      end

J
Jeremy Kemper 已提交
49 50 51
      attr_writer :silenced


52 53 54
      private
        def deprecation_message(callstack, message = nil)
          file, line, method = extract_callstack(callstack)
55 56
          message ||= "You are using deprecated behavior which will be removed from Rails 2.0."
          "DEPRECATION WARNING: #{message}  See http://www.rubyonrails.org/deprecation for details. (called from #{method} at #{file}:#{line})"
57 58 59 60
        end

        def extract_callstack(callstack)
          callstack.first.match(/^(.+?):(\d+)(?::in `(.*?)')?/).captures
61 62
        end
    end
63 64 65 66 67

    # Behavior is a block that takes a message argument.
    mattr_accessor :behavior
    self.behavior = default_behavior

68
    module ClassMethods
69 70 71 72 73
      # Declare that a method has been deprecated.
      def deprecate(*method_names)
        method_names.each do |method_name|
          class_eval(<<-EOS, __FILE__, __LINE__)
            def #{method_name}_with_deprecation(*args, &block)
74
              ::ActiveSupport::Deprecation.warn("#{method_name} is deprecated and will be removed from Rails 2.0", caller)
75 76 77 78
              #{method_name}_without_deprecation(*args, &block)
            end
          EOS
          alias_method_chain(method_name, :deprecation)
79 80 81
        end
      end
    end
82 83

    module Assertions
84
      def assert_deprecated(match = nil, &block)
85
        last = collect_deprecations(&block).last
86
        assert last, "Expected a deprecation warning within the block but received none"
87 88 89 90
        if match
          match = Regexp.new(Regexp.escape(match)) unless match.is_a?(Regexp)
          assert_match match, last, "Deprecation warning didn't match #{match}: #{last}"
        end
91 92 93
      end

      def assert_not_deprecated(&block)
94 95
        deprecations = collect_deprecations(&block)
        assert deprecations.empty?, "Expected no deprecation warning within the block but received #{deprecations.size}: \n  #{deprecations * "\n  "}"
96 97 98
      end

      private
99
        def collect_deprecations
100
          old_behavior = ActiveSupport::Deprecation.behavior
101
          deprecations = []
102
          ActiveSupport::Deprecation.behavior = Proc.new do |message, callstack|
103 104
            deprecations << message
          end
105
          yield
J
Jeremy Kemper 已提交
106
          deprecations
107 108 109 110
        ensure
          ActiveSupport::Deprecation.behavior = old_behavior
        end
    end
111 112 113 114 115 116 117 118 119 120

    # Stand-in for @request, @attributes, etc.
    class DeprecatedInstanceVariableProxy
      instance_methods.each { |m| undef_method m unless m =~ /^__/ }

      def initialize(instance, method, var = "@#{method}")
        @instance, @method, @var = instance, method, var
      end

      private
121 122 123 124
        def warn(callstack, called, args)
          ActiveSupport::Deprecation.warn("#{@var} is deprecated! Call #{@method}.#{called} instead of #{@var}.#{called}. Args: #{args.inspect}", callstack)
        end

125
        def method_missing(called, *args, &block)
126
          warn caller, called, args
127 128 129
          @instance.__send__(@method).__send__(called, *args, &block)
        end
    end
130 131 132
  end
end

133
class Module
134 135 136 137 138 139 140 141 142 143
  include ActiveSupport::Deprecation::ClassMethods
end

module Test
  module Unit
    class TestCase
      include ActiveSupport::Deprecation::Assertions
    end
  end
end