railtie.rb 5.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
13
  class Railtie < Rails::Railtie # :nodoc:
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

33 34
    config.active_record.use_schema_cache_dump = true

35 36
    config.eager_load_namespaces << ActiveRecord

37
    rake_tasks do
K
kennyj 已提交
38
      require "active_record/base"
39

40 41 42
      ActiveRecord::Tasks::DatabaseTasks.seed_loader = Rails.application
      ActiveRecord::Tasks::DatabaseTasks.env = Rails.env

43 44 45 46 47 48
      namespace :db do
        task :load_config do
          ActiveRecord::Tasks::DatabaseTasks.db_dir = Rails.application.config.paths["db"].first
          ActiveRecord::Tasks::DatabaseTasks.database_configuration = Rails.application.config.database_configuration
          ActiveRecord::Tasks::DatabaseTasks.migrations_paths = Rails.application.paths['db/migrate'].to_a
          ActiveRecord::Tasks::DatabaseTasks.fixtures_path = File.join Rails.root, 'test', 'fixtures'
49
          ActiveRecord::Tasks::DatabaseTasks.root = Rails.root
50 51 52 53 54 55

          if defined?(ENGINE_PATH) && engine = Rails::Engine.find(ENGINE_PATH)
            if engine.paths['db/migrate'].existent
              ActiveRecord::Tasks::DatabaseTasks.migrations_paths += engine.paths['db/migrate'].to_a
            end
          end
56 57 58
        end
      end

59
      load "active_record/railties/databases.rake"
60 61
    end

62 63 64
    # 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.
65 66
    console do |app|
      require "active_record/railties/console_sandbox" if app.sandbox?
K
kennyj 已提交
67
      require "active_record/base"
68
      console = ActiveSupport::Logger.new(STDERR)
69
      Rails.logger.extend ActiveSupport::Logger.broadcast console
70 71
    end

V
Vipul A M 已提交
72
    runner do
73 74 75
      require "active_record/base"
    end

76
    initializer "active_record.initialize_timezone" do
77
      ActiveSupport.on_load(:active_record) do
78 79 80
        self.time_zone_aware_attributes = true
        self.default_timezone = :utc
      end
81 82
    end

83
    initializer "active_record.logger" do
84
      ActiveSupport.on_load(:active_record) { self.logger ||= ::Rails.logger }
85 86
    end

V
Vipul A M 已提交
87
    initializer "active_record.migration_error" do
S
schneems 已提交
88 89 90 91 92 93
      if config.active_record.delete(:migration_error) == :page_load
        config.app_middleware.insert_after "::ActionDispatch::Callbacks",
          "ActiveRecord::Migration::CheckPending"
      end
    end

94
    initializer "active_record.check_schema_cache_dump" do
95 96 97 98
      if config.active_record.delete(:use_schema_cache_dump)
        config.after_initialize do |app|
          ActiveSupport.on_load(:active_record) do
            filename = File.join(app.config.paths["db"].first, "schema_cache.dump")
99

100 101 102
            if File.file?(filename)
              cache = Marshal.load File.binread filename
              if cache.version == ActiveRecord::Migrator.current_version
J
Jon Leighton 已提交
103
                self.connection.schema_cache = cache
104
              else
105
                warn "Ignoring db/schema_cache.dump because it has expired. The current schema version is #{ActiveRecord::Migrator.current_version}, but the one in the cache is #{cache.version}."
106 107 108 109 110 111 112
              end
            end
          end
        end
      end
    end

113
    initializer "active_record.set_configs" do |app|
114
      ActiveSupport.on_load(:active_record) do
115 116 117
        app.config.active_record.each do |k,v|
          send "#{k}=", v
        end
118 119 120 121 122 123
      end
    end

    # This sets the database configuration from Configuration#database_configuration
    # and then establishes the connection.
    initializer "active_record.initialize_database" do |app|
124
      ActiveSupport.on_load(:active_record) do
125
        self.configurations = app.config.database_configuration || {}
126 127
        establish_connection
      end
128 129
    end

130
    # Expose database runtime to controller for logging.
V
Vipul A M 已提交
131
    initializer "active_record.log_runtime" do
132
      require "active_record/railties/controller_runtime"
133
      ActiveSupport.on_load(:action_controller) do
134 135
        include ActiveRecord::Railties::ControllerRuntime
      end
136 137
    end

138
    initializer "active_record.set_reloader_hooks" do |app|
J
Jon Leighton 已提交
139
      hook = app.config.reload_classes_only_on_change ? :to_prepare : :to_cleanup
140

J
Jon Leighton 已提交
141 142
      ActiveSupport.on_load(:active_record) do
        ActionDispatch::Reloader.send(hook) do
143 144 145 146
          if ActiveRecord::Base.connected?
            ActiveRecord::Base.clear_reloadable_connections!
            ActiveRecord::Base.clear_cache!
          end
147
        end
148 149 150
      end
    end

151
    initializer "active_record.add_watchable_files" do |app|
152 153
      path = app.paths["db"].first
      config.watchable_files.concat ["#{path}/schema.rb", "#{path}/structure.sql"]
154
    end
155
  end
156
end