railtie.rb 4.7 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
K
kennyj 已提交
33
      require "active_record/base"
34
      load "active_record/railties/databases.rake"
35 36
    end

37 38 39
    # 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.
40 41
    console do |app|
      require "active_record/railties/console_sandbox" if app.sandbox?
K
kennyj 已提交
42
      require "active_record/base"
43
      console = ActiveSupport::Logger.new(STDERR)
44
      Rails.logger.extend ActiveSupport::Logger.broadcast console
45 46
    end

47 48 49 50
    runner do |app|
      require "active_record/base"
    end

51
    initializer "active_record.initialize_timezone" do
52
      ActiveSupport.on_load(:active_record) do
53 54 55
        self.time_zone_aware_attributes = true
        self.default_timezone = :utc
      end
56 57
    end

58
    initializer "active_record.logger" do
59
      ActiveSupport.on_load(:active_record) { self.logger ||= ::Rails.logger }
60 61
    end

S
schneems 已提交
62 63 64 65 66 67 68
    initializer "active_record.migration_error" do |app|
      if config.active_record.delete(:migration_error) == :page_load
        config.app_middleware.insert_after "::ActionDispatch::Callbacks",
          "ActiveRecord::Migration::CheckPending"
      end
    end

69
    initializer "active_record.set_configs" do |app|
70
      ActiveSupport.on_load(:active_record) do
71 72 73
        if app.config.active_record.delete(:whitelist_attributes)
          attr_accessible(nil)
        end
74 75 76
        app.config.active_record.each do |k,v|
          send "#{k}=", v
        end
77 78 79 80 81 82
      end
    end

    # This sets the database configuration from Configuration#database_configuration
    # and then establishes the connection.
    initializer "active_record.initialize_database" do |app|
83
      ActiveSupport.on_load(:active_record) do
84 85 86
        unless ENV['DATABASE_URL']
          self.configurations = app.config.database_configuration
        end
87 88
        establish_connection
      end
89 90
    end

91 92 93
    # Expose database runtime to controller for logging.
    initializer "active_record.log_runtime" do |app|
      require "active_record/railties/controller_runtime"
94
      ActiveSupport.on_load(:action_controller) do
95 96
        include ActiveRecord::Railties::ControllerRuntime
      end
97 98
    end

99
    initializer "active_record.set_reloader_hooks" do |app|
J
Jon Leighton 已提交
100
      hook = app.config.reload_classes_only_on_change ? :to_prepare : :to_cleanup
101

J
Jon Leighton 已提交
102 103 104 105
      ActiveSupport.on_load(:active_record) do
        ActionDispatch::Reloader.send(hook) do
          ActiveRecord::Base.clear_reloadable_connections!
          ActiveRecord::Base.clear_cache!
106
        end
107 108 109
      end
    end

110
    initializer "active_record.add_watchable_files" do |app|
111
      config.watchable_files.concat ["#{app.root}/db/schema.rb", "#{app.root}/db/structure.sql"]
112 113
    end

114
    config.after_initialize do |app|
115
      ActiveSupport.on_load(:active_record) do
J
Jon Leighton 已提交
116
        ActiveRecord::Base.instantiate_observers
117

J
José Valim 已提交
118
        ActionDispatch::Reloader.to_prepare do
119
          ActiveRecord::Base.instantiate_observers
120 121
        end
      end
122 123 124 125 126

      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)
127
            cache = Marshal.load File.binread filename
128 129 130 131 132
            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
133 134 135 136
          end
        end
      end

137 138
    end
  end
139
end