railtie.rb 4.6 KB
Newer Older
1 2 3 4
require "active_record"
require "rails"
require "active_model/railtie"

5 6 7 8
# For now, action_controller must always be present with
# rails, so let's make sure that it gets required before
# here. This is needed for correctly setting up the middleware.
# In the future, this might become an optional require.
C
Carl Lerche 已提交
9
require "action_controller/railtie"
10 11

module ActiveRecord
R
Rizwan Reza 已提交
12
  # = Active Record Railtie
C
Carl Lerche 已提交
13
  class Railtie < Rails::Railtie
14
    config.active_record = ActiveSupport::OrderedOptions.new
15

16
    config.app_generators.orm :active_record, :migration => true,
17
                                              :timestamps => true
18

19 20 21 22 23
    config.app_middleware.insert_after "::ActionDispatch::Callbacks",
      "ActiveRecord::QueryCache"

    config.app_middleware.insert_after "::ActionDispatch::Callbacks",
      "ActiveRecord::ConnectionAdapters::ConnectionManagement"
24

25 26 27 28 29 30 31
    config.action_dispatch.rescue_responses.merge!(
      'ActiveRecord::RecordNotFound'   => :not_found,
      'ActiveRecord::StaleObjectError' => :conflict,
      'ActiveRecord::RecordInvalid'    => :unprocessable_entity,
      'ActiveRecord::RecordNotSaved'   => :unprocessable_entity
    )

32
    rake_tasks do
33
      load "active_record/railties/databases.rake"
34 35
    end

36 37 38
    # When loading console, force ActiveRecord::Base to be loaded
    # to avoid cross references when loading a constant for the
    # first time. Also, make it output to STDERR.
39 40
    console do |app|
      require "active_record/railties/console_sandbox" if app.sandbox?
41
      console = ActiveSupport::Logger.new(STDERR)
42
      Rails.logger.extend ActiveSupport::Logger.broadcast console
43 44
    end

45
    initializer "active_record.initialize_timezone" do
46
      ActiveSupport.on_load(:active_record) do
47 48 49
        self.time_zone_aware_attributes = true
        self.default_timezone = :utc
      end
50 51
    end

52
    initializer "active_record.logger" do
53
      ActiveSupport.on_load(:active_record) { self.logger ||= ::Rails.logger }
54 55
    end

56
    initializer "active_record.set_configs" do |app|
57
      ActiveSupport.on_load(:active_record) do
58 59 60
        if app.config.active_record.delete(:whitelist_attributes)
          attr_accessible(nil)
        end
61 62 63
        app.config.active_record.each do |k,v|
          send "#{k}=", v
        end
64 65 66 67 68 69
      end
    end

    # This sets the database configuration from Configuration#database_configuration
    # and then establishes the connection.
    initializer "active_record.initialize_database" do |app|
70
      ActiveSupport.on_load(:active_record) do
71 72 73
        unless ENV['DATABASE_URL']
          self.configurations = app.config.database_configuration
        end
74 75
        establish_connection
      end
76 77
    end

78 79 80
    # Expose database runtime to controller for logging.
    initializer "active_record.log_runtime" do |app|
      require "active_record/railties/controller_runtime"
81
      ActiveSupport.on_load(:action_controller) do
82 83
        include ActiveRecord::Railties::ControllerRuntime
      end
84 85
    end

86 87 88 89 90 91 92 93 94 95 96 97 98
    initializer "active_record.set_reloader_hooks" do |app|
      hook = lambda do
        ActiveRecord::Base.clear_reloadable_connections!
        ActiveRecord::Base.clear_cache!
      end

      if app.config.reload_classes_only_on_change
        ActiveSupport.on_load(:active_record) do
          ActionDispatch::Reloader.to_prepare(&hook)
        end
      else
        ActiveSupport.on_load(:active_record) do
          ActionDispatch::Reloader.to_cleanup(&hook)
99
        end
100 101 102
      end
    end

103
    initializer "active_record.add_watchable_files" do |app|
104
      config.watchable_files.concat ["#{app.root}/db/schema.rb", "#{app.root}/db/structure.sql"]
105 106
    end

107
    config.after_initialize do |app|
108
      ActiveSupport.on_load(:active_record) do
J
Jon Leighton 已提交
109
        ActiveRecord::Base.instantiate_observers
110

J
José Valim 已提交
111
        ActionDispatch::Reloader.to_prepare do
112
          ActiveRecord::Base.instantiate_observers
113 114
        end
      end
115 116 117 118 119

      ActiveSupport.on_load(:active_record) do
        if app.config.use_schema_cache_dump
          filename = File.join(app.config.paths["db"].first, "schema_cache.dump")
          if File.file?(filename)
120
            cache = Marshal.load File.binread filename
121 122 123 124 125
            if cache.version == ActiveRecord::Migrator.current_version
              ActiveRecord::Base.connection.schema_cache = cache
            else
              warn "schema_cache.dump is expired. Current version is #{ActiveRecord::Migrator.current_version}, but cache version is #{cache.version}."
            end
126 127 128 129
          end
        end
      end

130
    end
131 132 133 134 135

    config.after_initialize do
      # We should load ActiveRecord::Base class before loading an application model.
      require "active_record/base"
    end
136
  end
137
end