railtie.rb 7.8 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
      ActiveRecord::Tasks::DatabaseTasks.env = Rails.env
41 42 43 44
      ActiveRecord::Tasks::DatabaseTasks.db_dir = Rails.application.config.paths["db"].first
      ActiveRecord::Tasks::DatabaseTasks.seed_loader = Rails.application
      ActiveRecord::Tasks::DatabaseTasks.database_configuration = Rails.application.config.database_configuration
      ActiveRecord::Tasks::DatabaseTasks.migrations_paths = Rails.application.paths['db/migrate'].to_a
45
      ActiveRecord::Tasks::DatabaseTasks.fixtures_path = File.join Rails.root, 'test', 'fixtures'
46

47
      if defined?(APP_RAKEFILE) && engine = Rails::Engine.find(find_engine_path(APP_RAKEFILE))
48 49 50 51 52
        if engine.paths['db/migrate'].existent
          ActiveRecord::Tasks::DatabaseTasks.migrations_paths += engine.paths['db/migrate'].to_a
        end
      end

53
      load "active_record/railties/databases.rake"
54 55
    end

56 57 58
    # 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.
59 60
    console do |app|
      require "active_record/railties/console_sandbox" if app.sandbox?
K
kennyj 已提交
61
      require "active_record/base"
62
      console = ActiveSupport::Logger.new(STDERR)
63
      Rails.logger.extend ActiveSupport::Logger.broadcast console
64 65
    end

V
Vipul A M 已提交
66
    runner do
67 68 69
      require "active_record/base"
    end

70
    initializer "active_record.initialize_timezone" do
71
      ActiveSupport.on_load(:active_record) do
72 73 74
        self.time_zone_aware_attributes = true
        self.default_timezone = :utc
      end
75 76
    end

77
    initializer "active_record.logger" do
78
      ActiveSupport.on_load(:active_record) { self.logger ||= ::Rails.logger }
79 80
    end

V
Vipul A M 已提交
81
    initializer "active_record.migration_error" do
S
schneems 已提交
82 83 84 85 86 87
      if config.active_record.delete(:migration_error) == :page_load
        config.app_middleware.insert_after "::ActionDispatch::Callbacks",
          "ActiveRecord::Migration::CheckPending"
      end
    end

88
    initializer "active_record.check_schema_cache_dump" do
89 90 91 92
      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")
93

94 95 96
            if File.file?(filename)
              cache = Marshal.load File.binread filename
              if cache.version == ActiveRecord::Migrator.current_version
J
Jon Leighton 已提交
97
                self.connection.schema_cache = cache
98
              else
99
                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}."
100 101 102 103 104 105 106
              end
            end
          end
        end
      end
    end

107
    initializer "active_record.set_configs" do |app|
108
      ActiveSupport.on_load(:active_record) do
109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128
        begin
          old_behavior, ActiveSupport::Deprecation.behavior = ActiveSupport::Deprecation.behavior, :stderr
          whitelist_attributes = app.config.active_record.delete(:whitelist_attributes)

          if respond_to?(:mass_assignment_sanitizer=)
            mass_assignment_sanitizer = nil
          else
            mass_assignment_sanitizer = app.config.active_record.delete(:mass_assignment_sanitizer)
          end

          unless whitelist_attributes.nil? && mass_assignment_sanitizer.nil?
            ActiveSupport::Deprecation.warn <<-EOF.strip_heredoc, []
              Model based mass assignment security has been extracted
              out of Rails into a gem. Please use the new recommended protection model for
              params or add `protected_attributes` to your Gemfile to use the old one.

              To disable this message remove the `whitelist_attributes` option from your
              `config/application.rb` file and any `mass_assignment_sanitizer` options
              from your `config/environments/*.rb` files.

129 130 131 132 133 134 135 136 137 138 139 140
              See http://guides.rubyonrails.org/security.html#mass-assignment for more information.
            EOF
          end

          unless app.config.active_record.delete(:auto_explain_threshold_in_seconds).nil?
            ActiveSupport::Deprecation.warn <<-EOF.strip_heredoc, []
              The Active Record auto explain feature has been removed.

              To disable this message remove the `active_record.auto_explain_threshold_in_seconds`
              option from the `config/environments/*.rb` config file.

              See http://guides.rubyonrails.org/4_0_release_notes.html for more information.
141 142
            EOF
          end
143 144 145 146

          unless app.config.active_record.delete(:observers).nil?
            ActiveSupport::Deprecation.warn <<-EOF.strip_heredoc, []
              Active Record Observers has been extracted out of Rails into a gem.
147
              Please use callbacks or add `rails-observers` to your Gemfile to use observers.
148 149 150 151

              To disable this message remove the `observers` option from your
              `config/application.rb` or from your initializers.

152
              See http://guides.rubyonrails.org/4_0_release_notes.html for more information.
153 154
            EOF
          end
155 156 157 158
        ensure
          ActiveSupport::Deprecation.behavior = old_behavior
        end

159 160 161
        app.config.active_record.each do |k,v|
          send "#{k}=", v
        end
162 163 164 165 166 167
      end
    end

    # This sets the database configuration from Configuration#database_configuration
    # and then establishes the connection.
    initializer "active_record.initialize_database" do |app|
168
      ActiveSupport.on_load(:active_record) do
169
        self.configurations = app.config.database_configuration || {}
170 171
        establish_connection
      end
172 173
    end

174
    # Expose database runtime to controller for logging.
V
Vipul A M 已提交
175
    initializer "active_record.log_runtime" do
176
      require "active_record/railties/controller_runtime"
177
      ActiveSupport.on_load(:action_controller) do
178 179
        include ActiveRecord::Railties::ControllerRuntime
      end
180 181
    end

182
    initializer "active_record.set_reloader_hooks" do |app|
J
Jon Leighton 已提交
183
      hook = app.config.reload_classes_only_on_change ? :to_prepare : :to_cleanup
184

J
Jon Leighton 已提交
185 186
      ActiveSupport.on_load(:active_record) do
        ActionDispatch::Reloader.send(hook) do
187 188 189 190
          if ActiveRecord::Base.connected?
            ActiveRecord::Base.clear_reloadable_connections!
            ActiveRecord::Base.clear_cache!
          end
191
        end
192 193 194
      end
    end

195
    initializer "active_record.add_watchable_files" do |app|
196 197
      path = app.paths["db"].first
      config.watchable_files.concat ["#{path}/schema.rb", "#{path}/structure.sql"]
198
    end
199
  end
200
end