rails 4.2.0.rc3 → 4.2.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA1:
3
- metadata.gz: ea9e895f8c4ef510761607e57925bb76d1d03cea
4
- data.tar.gz: 025cbb96cf14a5279bdd53f0087f56f14f7f99fa
3
+ metadata.gz: 820f40537f6670c1bf36f61979047ac3b8173437
4
+ data.tar.gz: 19860336f8213b3e83f09118a638d40a67b625bb
5
5
  SHA512:
6
- metadata.gz: 8c88af20de34bf3d26a06f6497a15e671ca60a8fa7fbb5a3f1eb90e0dae1f5b584a514e64b5fe3907cf340f500f50faff2110fd2784b3e6ef16d2915907e0eca
7
- data.tar.gz: 9644b1cd5497489d0e3382c9bd77cc0a82475c0dcfc42a312be10d4e4d8ec900799f2396bf2ade1d1362b576e689b3932fa7f63568c8e2189616ae70af94a97d
6
+ metadata.gz: 0d9aba1fdb1c9bcf61616777f57854700e8b58fde7a17eed6d39e5fed8e95751bccefc834a94aa2fd03e11f1aa4939dc7e7a48736d5e9dcda1b4ab28cc3ab094
7
+ data.tar.gz: 0c778c7b93788d1f30764afe47f47a761c423f7d501b322c56a6ed0f66cd2147f85eda2c3a6bbb92283ed792868f36b6e6b3c1f860a81cd169c354d0823a3336
@@ -1,3 +1,7 @@
1
+ * New guide about constant autoloading and reloading.
2
+
3
+ *Xavier Noria*
4
+
1
5
  * Change Posts to Articles in Getting Started sample application in order to
2
6
  better align with the actual guides.
3
7
 
@@ -3,8 +3,6 @@ unless File.exist?('Gemfile')
3
3
  source 'https://rubygems.org'
4
4
  gem 'rails', github: 'rails/rails'
5
5
  gem 'arel', github: 'rails/arel'
6
- gem 'rack', github: 'rack/rack'
7
- gem 'i18n', github: 'svenfuchs/i18n'
8
6
  GEMFILE
9
7
 
10
8
  system 'bundle'
@@ -3,8 +3,6 @@ unless File.exist?('Gemfile')
3
3
  source 'https://rubygems.org'
4
4
  gem 'rails', github: 'rails/rails'
5
5
  gem 'arel', github: 'rails/arel'
6
- gem 'rack', github: 'rack/rack'
7
- gem 'i18n', github: 'svenfuchs/i18n'
8
6
  gem 'sqlite3'
9
7
  GEMFILE
10
8
 
@@ -514,9 +514,9 @@ Please refer to the [Changelog][action-pack] for detailed changes.
514
514
  implementation and not an intentional feature, e.g.:
515
515
 
516
516
  ```ruby
517
-   test "list all posts" do
518
-     get "/posts"
519
-     assert_response :success 
517
+ test "list all posts" do
518
+ get "/posts"
519
+ assert_response :success
520
520
  end
521
521
  ```
522
522
 
@@ -640,6 +640,10 @@ Please refer to the [Changelog][active-record] for detailed changes.
640
640
  `Relation` for performing queries and updates is the preferred API.
641
641
  ([Commit](https://github.com/rails/rails/commit/d5902c9e))
642
642
 
643
+ * Deprecated `add_timestamps` and `t.timestamps` without passing the `:null`
644
+ option. The default of `null: true` will change in Rails 5 to `null: false`.
645
+ ([Pull Request](https://github.com/rails/rails/pull/16481))
646
+
643
647
  * Deprecated `Reflection#source_macro` without replacement as it is no longer
644
648
  needed in Active Record.
645
649
  ([Pull Request](https://github.com/rails/rails/pull/16373))
@@ -658,6 +662,9 @@ Please refer to the [Changelog][active-record] for detailed changes.
658
662
 
659
663
  ### Notable changes
660
664
 
665
+ * `SchemaDumper` uses `force: :cascade` on `create_table`. This makes it
666
+ possible to reload a schema when foreign keys are in place.
667
+
661
668
  * Added a `:required` option to singular associations, which defines a
662
669
  presence validation on the association.
663
670
  ([Pull Request](https://github.com/rails/rails/pull/16056))
@@ -824,6 +831,7 @@ Please refer to the [Changelog][active-support] for detailed changes.
824
831
  `module Foo; extend ActiveSupport::Concern; end` boilerplate.
825
832
  ([Commit](https://github.com/rails/rails/commit/b16c36e688970df2f96f793a759365b248b582ad))
826
833
 
834
+ * New [guide](constant_autoloading_and_reloading.html) about constant autoloading and reloading.
827
835
 
828
836
  Credits
829
837
  -------
@@ -358,7 +358,7 @@ class CreatePublications < ActiveRecord::Migration
358
358
  t.string :publisher_type
359
359
  t.boolean :single_issue
360
360
 
361
- t.timestamps
361
+ t.timestamps null: false
362
362
  end
363
363
  add_index :publications, :publication_type_id
364
364
  end
@@ -39,7 +39,7 @@ class CreateProducts < ActiveRecord::Migration
39
39
  t.string :name
40
40
  t.text :description
41
41
 
42
- t.timestamps
42
+ t.timestamps null: false
43
43
  end
44
44
  end
45
45
  end
@@ -285,7 +285,7 @@ class CreateProducts < ActiveRecord::Migration
285
285
  t.string :name
286
286
  t.text :description
287
287
 
288
- t.timestamps
288
+ t.timestamps null: false
289
289
  end
290
290
  end
291
291
  end
@@ -826,7 +826,7 @@ class CreateProducts < ActiveRecord::Migration
826
826
  create_table :products do |t|
827
827
  t.string :name
828
828
  t.text :description
829
- t.timestamps
829
+ t.timestamps null: false
830
830
  end
831
831
  end
832
832
 
@@ -167,9 +167,8 @@ directory. Files in this directory are served by the Sprockets middleware.
167
167
 
168
168
  Assets can still be placed in the `public` hierarchy. Any assets under `public`
169
169
  will be served as static files by the application or web server when
170
- `config.serve_static_assets` is set to true. You should use
171
- `app/assets` for files that must undergo some pre-processing before they are
172
- served.
170
+ `config.serve_static_files` is set to true. You should use `app/assets` for
171
+ files that must undergo some pre-processing before they are served.
173
172
 
174
173
  In production, Rails precompiles these files to `public/assets` by default. The
175
174
  precompiled copies are then served as static assets by the web server. The files
@@ -101,13 +101,13 @@ class CreateOrders < ActiveRecord::Migration
101
101
  def change
102
102
  create_table :customers do |t|
103
103
  t.string :name
104
- t.timestamps
104
+ t.timestamps null: false
105
105
  end
106
106
 
107
107
  create_table :orders do |t|
108
108
  t.belongs_to :customer, index: true
109
109
  t.datetime :order_date
110
- t.timestamps
110
+ t.timestamps null: false
111
111
  end
112
112
  end
113
113
  end
@@ -132,13 +132,13 @@ class CreateSuppliers < ActiveRecord::Migration
132
132
  def change
133
133
  create_table :suppliers do |t|
134
134
  t.string :name
135
- t.timestamps
135
+ t.timestamps null: false
136
136
  end
137
137
 
138
138
  create_table :accounts do |t|
139
139
  t.belongs_to :supplier, index: true
140
140
  t.string :account_number
141
- t.timestamps
141
+ t.timestamps null: false
142
142
  end
143
143
  end
144
144
  end
@@ -165,13 +165,13 @@ class CreateCustomers < ActiveRecord::Migration
165
165
  def change
166
166
  create_table :customers do |t|
167
167
  t.string :name
168
- t.timestamps
168
+ t.timestamps null: false
169
169
  end
170
170
 
171
171
  create_table :orders do |t|
172
172
  t.belongs_to :customer, index:true
173
173
  t.datetime :order_date
174
- t.timestamps
174
+ t.timestamps null: false
175
175
  end
176
176
  end
177
177
  end
@@ -207,19 +207,19 @@ class CreateAppointments < ActiveRecord::Migration
207
207
  def change
208
208
  create_table :physicians do |t|
209
209
  t.string :name
210
- t.timestamps
210
+ t.timestamps null: false
211
211
  end
212
212
 
213
213
  create_table :patients do |t|
214
214
  t.string :name
215
- t.timestamps
215
+ t.timestamps null: false
216
216
  end
217
217
 
218
218
  create_table :appointments do |t|
219
219
  t.belongs_to :physician, index: true
220
220
  t.belongs_to :patient, index: true
221
221
  t.datetime :appointment_date
222
- t.timestamps
222
+ t.timestamps null: false
223
223
  end
224
224
  end
225
225
  end
@@ -291,19 +291,19 @@ class CreateAccountHistories < ActiveRecord::Migration
291
291
  def change
292
292
  create_table :suppliers do |t|
293
293
  t.string :name
294
- t.timestamps
294
+ t.timestamps null: false
295
295
  end
296
296
 
297
297
  create_table :accounts do |t|
298
298
  t.belongs_to :supplier, index: true
299
299
  t.string :account_number
300
- t.timestamps
300
+ t.timestamps null: false
301
301
  end
302
302
 
303
303
  create_table :account_histories do |t|
304
304
  t.belongs_to :account, index: true
305
305
  t.integer :credit_rating
306
- t.timestamps
306
+ t.timestamps null: false
307
307
  end
308
308
  end
309
309
  end
@@ -332,12 +332,12 @@ class CreateAssembliesAndParts < ActiveRecord::Migration
332
332
  def change
333
333
  create_table :assemblies do |t|
334
334
  t.string :name
335
- t.timestamps
335
+ t.timestamps null: false
336
336
  end
337
337
 
338
338
  create_table :parts do |t|
339
339
  t.string :part_number
340
- t.timestamps
340
+ t.timestamps null: false
341
341
  end
342
342
 
343
343
  create_table :assemblies_parts, id: false do |t|
@@ -371,13 +371,13 @@ class CreateSuppliers < ActiveRecord::Migration
371
371
  def change
372
372
  create_table :suppliers do |t|
373
373
  t.string :name
374
- t.timestamps
374
+ t.timestamps null: false
375
375
  end
376
376
 
377
377
  create_table :accounts do |t|
378
378
  t.integer :supplier_id
379
379
  t.string :account_number
380
- t.timestamps
380
+ t.timestamps null: false
381
381
  end
382
382
 
383
383
  add_index :accounts, :supplier_id
@@ -455,7 +455,7 @@ class CreatePictures < ActiveRecord::Migration
455
455
  t.string :name
456
456
  t.integer :imageable_id
457
457
  t.string :imageable_type
458
- t.timestamps
458
+ t.timestamps null: false
459
459
  end
460
460
 
461
461
  add_index :pictures, :imageable_id
@@ -471,7 +471,7 @@ class CreatePictures < ActiveRecord::Migration
471
471
  create_table :pictures do |t|
472
472
  t.string :name
473
473
  t.references :imageable, polymorphic: true, index: true
474
- t.timestamps
474
+ t.timestamps null: false
475
475
  end
476
476
  end
477
477
  end
@@ -501,7 +501,7 @@ class CreateEmployees < ActiveRecord::Migration
501
501
  def change
502
502
  create_table :employees do |t|
503
503
  t.references :manager, index: true
504
- t.timestamps
504
+ t.timestamps null: false
505
505
  end
506
506
  end
507
507
  end
@@ -120,7 +120,7 @@ numbers. New applications filter out passwords by adding the following `config.f
120
120
 
121
121
  * `secrets.secret_key_base` is used for specifying a key which allows sessions for the application to be verified against a known secure key to prevent tampering. Applications get `secrets.secret_key_base` initialized to a random key present in `config/secrets.yml`.
122
122
 
123
- * `config.serve_static_assets` configures Rails itself to serve static assets. Defaults to true, but in the production environment is turned off as the server software (e.g. NGINX or Apache) used to run the application should serve static assets instead. Unlike the default setting set this to true when running (absolutely not recommended!) or testing your app in production mode using WEBrick. Otherwise you won't be able use page caching and requests for files that exist regularly under the public directory will anyway hit your Rails app.
123
+ * `config.serve_static_files` configures Rails itself to serve static files. Defaults to true, but in the production environment is turned off as the server software (e.g. NGINX or Apache) used to run the application should serve static assets instead. Unlike the default setting set this to true when running (absolutely not recommended!) or testing your app in production mode using WEBrick. Otherwise you won't be able use page caching and requests for files that exist regularly under the public directory will anyway hit your Rails app.
124
124
 
125
125
  * `config.session_store` is usually set up in `config/initializers/session_store.rb` and specifies what class to use to store the session. Possible values are `:cookie_store` which is the default, `:mem_cache_store`, and `:disabled`. The last one tells Rails not to deal with sessions. Custom session stores can also be specified:
126
126
 
@@ -0,0 +1,1297 @@
1
+ Constant Autoloading and Reloading
2
+ ==================================
3
+
4
+ This guide documents how constant autoloading and reloading works.
5
+
6
+ After reading this guide, you will know:
7
+
8
+ * Key aspects of Ruby constants
9
+ * What is `autoload_paths`
10
+ * How constant autoloading works
11
+ * What is `require_dependency`
12
+ * How constant reloading works
13
+ * Solutions to common autoloading gotchas
14
+
15
+ --------------------------------------------------------------------------------
16
+
17
+
18
+ Introduction
19
+ ------------
20
+
21
+ Ruby on Rails allows applications to be written as if their code was preloaded.
22
+
23
+ In a normal Ruby program classes need to load their dependencies:
24
+
25
+ ```ruby
26
+ require 'application_controller'
27
+ require 'post'
28
+
29
+ class PostsController < ApplicationController
30
+ def index
31
+ @posts = Post.all
32
+ end
33
+ end
34
+ ```
35
+
36
+ Our Rubyist instinct quickly sees some redundancy in there: If classes were
37
+ defined in files matching their name, couldn't their loading be automated
38
+ somehow? We could save scanning the file for dependencies, which is brittle.
39
+
40
+ Moreover, `Kernel#require` loads files once, but development is much more smooth
41
+ if code gets refreshed when it changes without restarting the server. It would
42
+ be nice to be able to use `Kernel#load` in development, and `Kernel#require` in
43
+ production.
44
+
45
+ Indeed, those features are provided by Ruby on Rails, where we just write
46
+
47
+ ```ruby
48
+ class PostsController < ApplicationController
49
+ def index
50
+ @posts = Post.all
51
+ end
52
+ end
53
+ ```
54
+
55
+ This guide documents how that works.
56
+
57
+
58
+ Constants Refresher
59
+ -------------------
60
+
61
+ While constants are trivial in most programming languages, they are a rich
62
+ topic in Ruby.
63
+
64
+ It is beyond the scope of this guide to document Ruby constants, but we are
65
+ nevertheless going to highlight a few key topics. Truly grasping the following
66
+ sections is instrumental to understanding constant autoloading and reloading.
67
+
68
+ ### Nesting
69
+
70
+ Class and module definitions can be nested to create namespaces:
71
+
72
+ ```ruby
73
+ module XML
74
+ class SAXParser
75
+ # (1)
76
+ end
77
+ end
78
+ ```
79
+
80
+ The *nesting* at any given place is the collection of enclosing nested class and
81
+ module objects outwards. For example, in the previous example, the nesting at
82
+ (1) is
83
+
84
+ ```ruby
85
+ [XML::SAXParser, XML]
86
+ ```
87
+
88
+ It is important to understand that the nesting is composed of class and module
89
+ *objects*, it has nothing to do with the constants used to access them, and is
90
+ also unrelated to their names.
91
+
92
+ For instance, while this definition is similar to the previous one:
93
+
94
+ ```ruby
95
+ class XML::SAXParser
96
+ # (2)
97
+ end
98
+ ```
99
+
100
+ the nesting in (2) is different:
101
+
102
+ ```ruby
103
+ [XML::SAXParser]
104
+ ```
105
+
106
+ `XML` does not belong to it.
107
+
108
+ We can see in this example that the name of a class or module that belongs to a
109
+ certain nesting does not necessarily correlate with the namespaces at the spot.
110
+
111
+ Even more, they are totally independent, take for instance
112
+
113
+ ```ruby
114
+ module X::Y
115
+ module A::B
116
+ # (3)
117
+ end
118
+ end
119
+ ```
120
+
121
+ The nesting in (3) consists of two module objects:
122
+
123
+ ```ruby
124
+ [A::B, X::Y]
125
+ ```
126
+
127
+ So, it not only doesn't end in `A`, which does not even belong to the nesting,
128
+ but it also contains `X::Y`, which is independent from `A::B`.
129
+
130
+ The nesting is an internal stack maintained by the interpreter, and it gets
131
+ modified according to these rules:
132
+
133
+ * The class object following a `class` keyword gets pushed when its body is
134
+ executed, and popped after it.
135
+
136
+ * The module object following a `module` keyword gets pushed when its body is
137
+ executed, and popped after it.
138
+
139
+ * A singleton class opened with `class << object` gets pushed, and popped later.
140
+
141
+ * When any of the `*_eval` family of methods is called using a string argument,
142
+ the singleton class of the receiver is pushed to the nesting of the eval'ed
143
+ code.
144
+
145
+ * The nesting at the top-level of code interpreted by `Kernel#load` is empty
146
+ unless the `load` call receives a true value as second argument, in which case
147
+ a newly created anonymous module is pushed by Ruby.
148
+
149
+ It is interesting to observe that blocks do not modify the stack. In particular
150
+ the blocks that may be passed to `Class.new` and `Module.new` do not get the
151
+ class or module being defined pushed to their nesting. That's one of the
152
+ differences between defining classes and modules in one way or another.
153
+
154
+ The nesting at any given place can be inspected with `Module.nesting`.
155
+
156
+ ### Class and Module Definitions are Constant Assignments
157
+
158
+ Let's suppose the following snippet creates a class (rather than reopening it):
159
+
160
+ ```ruby
161
+ class C
162
+ end
163
+ ```
164
+
165
+ Ruby creates a constant `C` in `Object` and stores in that constant a class
166
+ object. The name of the class instance is "C", a string, named after the
167
+ constant.
168
+
169
+ That is,
170
+
171
+ ```ruby
172
+ class Project < ActiveRecord::Base
173
+ end
174
+ ```
175
+
176
+ performs a constant assignment equivalent to
177
+
178
+ ```ruby
179
+ Project = Class.new(ActiveRecord::Base)
180
+ ```
181
+
182
+ including setting the name of the class as a side-effect:
183
+
184
+ ```ruby
185
+ Project.name # => "Project"
186
+ ```
187
+
188
+ Constant assignment has a special rule to make that happen: if the object
189
+ being assigned is an anonymous class or module, Ruby sets its name to be the
190
+ one the constant.
191
+
192
+ INFO. From then on, what happens to the constant and the instance does not
193
+ matter. For example, the constant could be deleted, the class object could be
194
+ assigned to a different constant, be stored in no constant anymore, etc. Once
195
+ the name is set, it doesn't change.
196
+
197
+ Similarly, module creation using the `module` keyword as in
198
+
199
+ ```ruby
200
+ module Admin
201
+ end
202
+ ```
203
+
204
+ performs a constant assignment equivalent to
205
+
206
+ ```ruby
207
+ Admin = Module.new
208
+ ```
209
+
210
+ including setting the name as a side-effect:
211
+
212
+ ```ruby
213
+ Admin.name # => "Admin"
214
+ ```
215
+
216
+ WARNING. The execution context of a block passed to `Class.new` or `Module.new`
217
+ is not entirely equivalent to the one of the body of the definitions using the
218
+ `class` and `module` keywords. But both idioms result in the same constant
219
+ assignment.
220
+
221
+ Thus, when one informally says "the `String` class", that really means: the
222
+ class object stored in the constant called "String" in the class object stored
223
+ in the `Object` constant. `String` is otherwise an ordinary Ruby constant and
224
+ everything related to constants applies to it, resolution algorithms, etc.
225
+
226
+ Likewise, in the controller
227
+
228
+ ```ruby
229
+ class PostsController < ApplicationController
230
+ def index
231
+ @posts = Post.all
232
+ end
233
+ end
234
+ ```
235
+
236
+ `Post` is not syntax for a class. Rather, `Post` is a regular Ruby constant. If
237
+ all is good, the constant evaluates to an object that responds to `all`.
238
+
239
+ That is why we talk about *constant* autoloading, Rails has the ability to
240
+ load constants on the fly.
241
+
242
+ ### Constants are Stored in Modules
243
+
244
+ Constants belong to modules in a very literal sense. Classes and modules have
245
+ a constant table; think of it as a hash table.
246
+
247
+ Let's analyze an example to really understand what that means. While common
248
+ abuses of language like "the `String` class" are convenient, the exposition is
249
+ going to be precise here for didactic purposes.
250
+
251
+ Let's consider the following module definition:
252
+
253
+ ```ruby
254
+ module Colors
255
+ RED = '0xff0000'
256
+ end
257
+ ```
258
+
259
+ First, when the `module` keyword is processed the interpreter creates a new
260
+ entry in the constant table of the class object stored in the `Object` constant.
261
+ Said entry associates the name "Colors" to a newly created module object.
262
+ Furthermore, the interpreter sets the name of the new module object to be the
263
+ string "Colors".
264
+
265
+ Later, when the body of the module definition is interpreted, a new entry is
266
+ created in the constant table of the module object stored in the `Colors`
267
+ constant. That entry maps the name "RED" to the string "0xff0000".
268
+
269
+ In particular, `Colors::RED` is totally unrelated to any other `RED` constant
270
+ that may live in any other class or module object. If there were any, they
271
+ would have separate entries in their respective constant tables.
272
+
273
+ Put special attention in the previous paragraphs to the distinction between
274
+ class and module objects, constant names, and value objects associated to them
275
+ in constant tables.
276
+
277
+ ### Resolution Algorithms
278
+
279
+ #### Resolution Algorithm for Relative Constants
280
+
281
+ At any given place in the code, let's define *cref* to be the first element of
282
+ the nesting if it is not empty, or `Object` otherwise.
283
+
284
+ Without getting too much into the details, the resolution algorithm for relative
285
+ constant references goes like this:
286
+
287
+ 1. If the nesting is not empty the constant is looked up in its elements and in
288
+ order. The ancestors of those elements are ignored.
289
+
290
+ 2. If not found, then the algorithm walks up the ancestor chain of the cref.
291
+
292
+ 3. If not found, `const_missing` is invoked on the cref. The default
293
+ implementation of `const_missing` raises `NameError`, but it can be overridden.
294
+
295
+ Rails autoloading **does not emulate this algorithm**, but its starting point is
296
+ the name of the constant to be autoloaded, and the cref. See more in [Relative
297
+ References](#relative-references).
298
+
299
+ #### Resolution Algorithm for Qualified Constants
300
+
301
+ Qualified constants look like this:
302
+
303
+ ```ruby
304
+ Billing::Invoice
305
+ ```
306
+
307
+ `Billing::Invoice` is composed of two constants: `Billing` is relative and is
308
+ resolved using the algorithm of the previous section.
309
+
310
+ INFO. Leading colons would make the first segment absolute rather than
311
+ relative: `::Billing::Invoice`. That would force `Billing` to be looked up
312
+ only as a top-level constant.
313
+
314
+ `Invoice` on the other hand is qualified by `Billing` and we are going to see
315
+ its resolution next. Let's call *parent* to that qualifying class or module
316
+ object, that is, `Billing` in the example above. The algorithm for qualified
317
+ constants goes like this:
318
+
319
+ 1. The constant is looked up in the parent and its ancestors.
320
+
321
+ 2. If the lookup fails, `const_missing` is invoked in the parent. The default
322
+ implementation of `const_missing` raises `NameError`, but it can be overridden.
323
+
324
+ As you see, this algorithm is simpler than the one for relative constants. In
325
+ particular, the nesting plays no role here, and modules are not special-cased,
326
+ if neither they nor their ancestors have the constants, `Object` is **not**
327
+ checked.
328
+
329
+ Rails autoloading **does not emulate this algorithm**, but its starting point is
330
+ the name of the constant to be autoloaded, and the parent. See more in
331
+ [Qualified References](#qualified-references).
332
+
333
+
334
+ Vocabulary
335
+ ----------
336
+
337
+ ### Parent Namespaces
338
+
339
+ Given a string with a constant path we define its *parent namespace* to be the
340
+ string that results from removing its rightmost segment.
341
+
342
+ For example, the parent namespace of the string "A::B::C" is the string "A::B",
343
+ the parent namespace of "A::B" is "A", and the parent namespace of "A" is "".
344
+
345
+ The interpretation of a parent namespace when thinking about classes and modules
346
+ is tricky though. Let's consider a module M named "A::B":
347
+
348
+ * The parent namespace, "A", may not reflect nesting at a given spot.
349
+
350
+ * The constant `A` may no longer exist, some code could have removed it from
351
+ `Object`.
352
+
353
+ * If `A` exists, the class or module that was originally in `A` may not be there
354
+ anymore. For example, if after a constant removal there was another constant
355
+ assignment there would generally be a different object in there.
356
+
357
+ * In such case, it could even happen that the reassigned `A` held a new class or
358
+ module called also "A"!
359
+
360
+ * In the previous scenarios M would no longer be reachable through `A::B` but
361
+ the module object itself could still be alive somewhere and its name would
362
+ still be "A::B".
363
+
364
+ The idea of a parent namespace is at the core of the autoloading algorithms
365
+ and helps explain and understand their motivation intuitively, but as you see
366
+ that metaphor leaks easily. Given an edge case to reason about, take always into
367
+ account that by "parent namespace" the guide means exactly that specific string
368
+ derivation.
369
+
370
+ ### Loading Mechanism
371
+
372
+ Rails autoloads files with `Kernel#load` when `config.cache_classes` is false,
373
+ the default in development mode, and with `Kernel#require` otherwise, the
374
+ default in production mode.
375
+
376
+ `Kernel#load` allows Rails to execute files more than once if [constant
377
+ reloading](#constant-reloading) is enabled.
378
+
379
+ This guide uses the word "load" freely to mean a given file is interpreted, but
380
+ the actual mechanism can be `Kernel#load` or `Kernel#require` depending on that
381
+ flag.
382
+
383
+
384
+ Autoloading Availability
385
+ ------------------------
386
+
387
+ Rails is always able to autoload provided its environment is in place. For
388
+ example the `runner` command autoloads:
389
+
390
+ ```
391
+ $ bin/rails runner 'p User.column_names'
392
+ ["id", "email", "created_at", "updated_at"]
393
+ ```
394
+
395
+ The console autoloads, the test suite autoloads, and of course the application
396
+ autoloads.
397
+
398
+ By default, Rails eager loads the application files when it boots in production
399
+ mode, so most of the autoloading going on in development does not happen. But
400
+ autoloading may still be triggered during eager loading.
401
+
402
+ For example, given
403
+
404
+ ```ruby
405
+ class BeachHouse < House
406
+ end
407
+ ```
408
+
409
+ if `House` is still unknown when `app/models/beach_house.rb` is being eager
410
+ loaded, Rails autoloads it.
411
+
412
+
413
+ autoload_paths
414
+ --------------
415
+
416
+ As you probably know, when `require` gets a relative file name:
417
+
418
+ ```ruby
419
+ require 'erb'
420
+ ```
421
+
422
+ Ruby looks for the file in the directories listed in `$LOAD_PATH`. That is, Ruby
423
+ iterates over all its directories and for each one of them checks whether they
424
+ have a file called "erb.rb", or "erb.so", or "erb.o", or "erb.dll". If it finds
425
+ any of them, the interpreter loads it and ends the search. Otherwise, it tries
426
+ again in the next directory of the list. If the list gets exhausted, `LoadError`
427
+ is raised.
428
+
429
+ We are going to cover how constant autoloading works in more detail later, but
430
+ the idea is that when a constant like `Post` is hit and missing, if there's a
431
+ `post.rb` file for example in `app/models` Rails is going to find it, evaluate
432
+ it, and have `Post` defined as a side-effect.
433
+
434
+ Alright, Rails has a collection of directories similar to `$LOAD_PATH` in which
435
+ to look up `post.rb`. That collection is called `autoload_paths` and by
436
+ default it contains:
437
+
438
+ * All subdirectories of `app` in the application and engines. For example,
439
+ `app/controllers`. They do not need to be the default ones, any custom
440
+ directories like `app/workers` belong automatically to `autoload_paths`.
441
+
442
+ * Any existing second level directories called `app/*/concerns` in the
443
+ application and engines.
444
+
445
+ * The directory `test/mailers/previews`.
446
+
447
+ Also, this collection is configurable via `config.autoload_paths`. For example,
448
+ `lib` was in the list years ago, but no longer is. An application can opt-in
449
+ throwing this to `config/application.rb`:
450
+
451
+ ```ruby
452
+ config.autoload_paths += "#{Rails.root}/lib"
453
+ ```
454
+
455
+ The value of `autoload_paths` can be inspected. In a just generated application
456
+ it is (edited):
457
+
458
+ ```
459
+ $ bin/rails r 'puts ActiveSupport::Dependencies.autoload_paths'
460
+ .../app/assets
461
+ .../app/controllers
462
+ .../app/helpers
463
+ .../app/mailers
464
+ .../app/models
465
+ .../app/controllers/concerns
466
+ .../app/models/concerns
467
+ .../test/mailers/previews
468
+ ```
469
+
470
+ INFO. `autoload_paths` is computed and cached during the initialization process.
471
+ The application needs to be restarted to reflect any changes in the directory
472
+ structure.
473
+
474
+
475
+ Autoloading Algorithms
476
+ ----------------------
477
+
478
+ ### Relative References
479
+
480
+ A relative constant reference may appear in several places, for example, in
481
+
482
+ ```ruby
483
+ class PostsController < ApplicationController
484
+ def index
485
+ @posts = Post.all
486
+ end
487
+ end
488
+ ```
489
+
490
+ all three constant references are relative.
491
+
492
+ #### Constants after the `class` and `module` Keywords
493
+
494
+ Ruby performs a lookup for the constant that follows a `class` or `module`
495
+ keyword because it needs to know if the class or module is going to be created
496
+ or reopened.
497
+
498
+ If the constant is not defined at that point it is not considered to be a
499
+ missing constant, autoloading is **not** triggered.
500
+
501
+ So, in the previous example, if `PostsController` is not defined when the file
502
+ is interpreted Rails autoloading is not going to be triggered, Ruby will just
503
+ define the controller.
504
+
505
+ #### Top-Level Constants
506
+
507
+ On the contrary, if `ApplicationController` is unknown, the constant is
508
+ considered missing and an autoload is going to be attempted by Rails.
509
+
510
+ In order to load `ApplicationController`, Rails iterates over `autoload_paths`.
511
+ First checks if `app/assets/application_controller.rb` exists. If it does not,
512
+ which is normally the case, it continues and finds
513
+ `app/controllers/application_controller.rb`.
514
+
515
+ If the file defines the constant `ApplicationController` all is fine, otherwise
516
+ `LoadError` is raised:
517
+
518
+ ```
519
+ unable to autoload constant ApplicationController, expected
520
+ <full path to application_controller.rb> to define it (LoadError)
521
+ ```
522
+
523
+ INFO. Rails does not require the value of autoloaded constants to be a class or
524
+ module object. For example, if the file `app/models/max_clients.rb` defines
525
+ `MAX_CLIENTS = 100` autoloading `MAX_CLIENTS` works just fine.
526
+
527
+ #### Namespaces
528
+
529
+ Autoloading `ApplicationController` looks directly under the directories of
530
+ `autoload_paths` because the nesting in that spot is empty. The situation of
531
+ `Post` is different, the nesting in that line is `[PostsController]` and support
532
+ for namespaces comes into play.
533
+
534
+ The basic idea is that given
535
+
536
+ ```ruby
537
+ module Admin
538
+ class BaseController < ApplicationController
539
+ @@all_roles = Role.all
540
+ end
541
+ end
542
+ ```
543
+
544
+ to autoload `Role` we are going to check if it is defined in the current or
545
+ parent namespaces, one at a time. So, conceptually we want to try to autoload
546
+ any of
547
+
548
+ ```
549
+ Admin::BaseController::Role
550
+ Admin::Role
551
+ Role
552
+ ```
553
+
554
+ in that order. That's the idea. To do so, Rails looks in `autoload_paths`
555
+ respectively for file names like these:
556
+
557
+ ```
558
+ admin/base_controller/role.rb
559
+ admin/role.rb
560
+ role.rb
561
+ ```
562
+
563
+ modulus some additional directory lookups we are going to cover soon.
564
+
565
+ INFO. `'Constant::Name'.underscore` gives the relative path without extension of
566
+ the file name where `Constant::Name` is expected to be defined.
567
+
568
+ Let's see how Rails autoloads the `Post` constant in the `PostsController`
569
+ above assuming the application has a `Post` model defined in
570
+ `app/models/post.rb`.
571
+
572
+ First it checks for `posts_controller/post.rb` in `autoload_paths`:
573
+
574
+ ```
575
+ app/assets/posts_controller/post.rb
576
+ app/controllers/posts_controller/post.rb
577
+ app/helpers/posts_controller/post.rb
578
+ ...
579
+ test/mailers/previews/posts_controller/post.rb
580
+ ```
581
+
582
+ Since the lookup is exhausted without success, a similar search for a directory
583
+ is performed, we are going to see why in the [next section](#automatic-modules):
584
+
585
+ ```
586
+ app/assets/posts_controller/post
587
+ app/controllers/posts_controller/post
588
+ app/helpers/posts_controller/post
589
+ ...
590
+ test/mailers/previews/posts_controller/post
591
+ ```
592
+
593
+ If all those attempts fail, then Rails starts the lookup again in the parent
594
+ namespace. In this case only the top-level remains:
595
+
596
+ ```
597
+ app/assets/post.rb
598
+ app/controllers/post.rb
599
+ app/helpers/post.rb
600
+ app/mailers/post.rb
601
+ app/models/post.rb
602
+ ```
603
+
604
+ A matching file is found in `app/models/post.rb`. The lookup stops there and the
605
+ file is loaded. If the file actually defines `Post` all is fine, otherwise
606
+ `LoadError` is raised.
607
+
608
+ ### Qualified References
609
+
610
+ When a qualified constant is missing Rails does not look for it in the parent
611
+ namespaces. But there is a caveat: When a constant is missing, Rails is
612
+ unable to tell if the trigger was a relative reference or a qualified one.
613
+
614
+ For example, consider
615
+
616
+ ```ruby
617
+ module Admin
618
+ User
619
+ end
620
+ ```
621
+
622
+ and
623
+
624
+ ```ruby
625
+ Admin::User
626
+ ```
627
+
628
+ If `User` is missing, in either case all Rails knows is that a constant called
629
+ "User" was missing in a module called "Admin".
630
+
631
+ If there is a top-level `User` Ruby would resolve it in the former example, but
632
+ wouldn't in the latter. In general, Rails does not emulate the Ruby constant
633
+ resolution algorithms, but in this case it tries using the following heuristic:
634
+
635
+ > If none of the parent namespaces of the class or module has the missing
636
+ > constant then Rails assumes the reference is relative. Otherwise qualified.
637
+
638
+ For example, if this code triggers autoloading
639
+
640
+ ```ruby
641
+ Admin::User
642
+ ```
643
+
644
+ and the `User` constant is already present in `Object`, it is not possible that
645
+ the situation is
646
+
647
+ ```ruby
648
+ module Admin
649
+ User
650
+ end
651
+ ```
652
+
653
+ because otherwise Ruby would have resolved `User` and no autoloading would have
654
+ been triggered in the first place. Thus, Rails assumes a qualified reference and
655
+ considers the file `admin/user.rb` and directory `admin/user` to be the only
656
+ valid options.
657
+
658
+ In practice, this works quite well as long as the nesting matches all parent
659
+ namespaces respectively and the constants that make the rule apply are known at
660
+ that time.
661
+
662
+ However, autoloading happens on demand. If by chance the top-level `User` was
663
+ not yet loaded, then Rails assumes a relative reference by contract.
664
+
665
+ Naming conflicts of this kind are rare in practice, but if one occurs,
666
+ `require_dependency` provides a solution by ensuring that the constant needed
667
+ to trigger the heuristic is defined in the conflicting place.
668
+
669
+ ### Automatic Modules
670
+
671
+ When a module acts as a namespace, Rails does not require the application to
672
+ defines a file for it, a directory matching the namespace is enough.
673
+
674
+ Suppose an application has a back office whose controllers are stored in
675
+ `app/controllers/admin`. If the `Admin` module is not yet loaded when
676
+ `Admin::UsersController` is hit, Rails needs first to autoload the constant
677
+ `Admin`.
678
+
679
+ If `autoload_paths` has a file called `admin.rb` Rails is going to load that
680
+ one, but if there's no such file and a directory called `admin` is found, Rails
681
+ creates an empty module and assigns it to the `Admin` constant on the fly.
682
+
683
+ ### Generic Procedure
684
+
685
+ Relative references are reported to be missing in the cref where they were hit,
686
+ and qualified references are reported to be missing in their parent. (See
687
+ [Resolution Algorithm for Relative
688
+ Constants](#resolution-algorithm-for-relative-constants) at the beginning of
689
+ this guide for the definition of *cref*, and [Resolution Algorithm for Qualified
690
+ Constants](#resolution-algorithm-for-qualified-constants) for the definition of
691
+ *parent*.)
692
+
693
+ The procedure to autoload constant `C` in an arbitrary situation is as follows:
694
+
695
+ ```
696
+ if the class or module in which C is missing is Object
697
+ let ns = ''
698
+ else
699
+ let M = the class or module in which C is missing
700
+
701
+ if M is anonymous
702
+ let ns = ''
703
+ else
704
+ let ns = M.name
705
+ end
706
+ end
707
+
708
+ loop do
709
+ # Look for a regular file.
710
+ for dir in autoload_paths
711
+ if the file "#{dir}/#{ns.underscore}/c.rb" exists
712
+ load/require "#{dir}/#{ns.underscore}/c.rb"
713
+
714
+ if C is now defined
715
+ return
716
+ else
717
+ raise LoadError
718
+ end
719
+ end
720
+ end
721
+
722
+ # Look for an automatic module.
723
+ for dir in autoload_paths
724
+ if the directory "#{dir}/#{ns.underscore}/c" exists
725
+ if ns is an empty string
726
+ let C = Module.new in Object and return
727
+ else
728
+ let C = Module.new in ns.constantize and return
729
+ end
730
+ end
731
+ end
732
+
733
+ if ns is empty
734
+ # We reached the top-level without finding the constant.
735
+ raise NameError
736
+ else
737
+ if C exists in any of the parent namespaces
738
+ # Qualified constants heuristic.
739
+ raise NameError
740
+ else
741
+ # Try again in the parent namespace.
742
+ let ns = the parent namespace of ns and retry
743
+ end
744
+ end
745
+ end
746
+ ```
747
+
748
+
749
+ require_dependency
750
+ ------------------
751
+
752
+ Constant autoloading is triggered on demand and therefore code that uses a
753
+ certain constant may have it already defined or may trigger an autoload. That
754
+ depends on the execution path and it may vary between runs.
755
+
756
+ There are times, however, in which you want to make sure a certain constant is
757
+ known when the execution reaches some code. `require_dependency` provides a way
758
+ to load a file using the current [loading mechanism](#loading-mechanism), and
759
+ keeping track of constants defined in that file as if they were autoloaded to
760
+ have them reloaded as needed.
761
+
762
+ `require_dependency` is rarely needed, but see a couple of use-cases in
763
+ [Autoloading and STI](#autoloading-and-sti) and [When Constants aren't
764
+ Triggered](#when-constants-aren-t-missed).
765
+
766
+ WARNING. Unlike autoloading, `require_dependency` does not expect the file to
767
+ define any particular constant. Exploiting this behavior would be a bad practice
768
+ though, file and constant paths should match.
769
+
770
+
771
+ Constant Reloading
772
+ ------------------
773
+
774
+ When `config.cache_classes` is false Rails is able to reload autoloaded
775
+ constants.
776
+
777
+ For example, in you're in a console session and edit some file behind the
778
+ scenes, the code can be reloaded with the `reload!` command:
779
+
780
+ ```
781
+ > reload!
782
+ ```
783
+
784
+ When the application runs, code is reloaded when something relevant to this
785
+ logic changes. In order to do that, Rails monitors a number of things:
786
+
787
+ * `config/routes.rb`.
788
+
789
+ * Locales.
790
+
791
+ * Ruby files under `autoload_paths`.
792
+
793
+ * `db/schema.rb` and `db/structure.sql`.
794
+
795
+ If anything in there changes, there is a middleware that detects it and reloads
796
+ the code.
797
+
798
+ Autoloading keeps track of autoloaded constants. Reloading is implemented by
799
+ removing them all from their respective classes and modules using
800
+ `Module#remove_const`. That way, when the code goes on, those constants are
801
+ going to be unknown again, and files reloaded on demand.
802
+
803
+ INFO. This is an all-or-nothing operation, Rails does not attempt to reload only
804
+ what changed since dependencies between classes makes that really tricky.
805
+ Instead, everything is wiped.
806
+
807
+
808
+ Module#autoload isn't Involved
809
+ ------------------------------
810
+
811
+ `Module#autoload` provides a lazy way to load constants that is fully integrated
812
+ with the Ruby constant lookup algorithms, dynamic constant API, etc. It is quite
813
+ transparent.
814
+
815
+ Rails internals make extensive use of it to defer as much work as possible from
816
+ the boot process. But constant autoloading in Rails is **not** implemented with
817
+ `Module#autoload`.
818
+
819
+ One possible implementation based on `Module#autoload` would be to walk the
820
+ application tree and issue `autoload` calls that map existing file names to
821
+ their conventional constant name.
822
+
823
+ There are a number of reasons that prevent Rails from using that implementation.
824
+
825
+ For example, `Module#autoload` is only capable of loading files using `require`,
826
+ so reloading would not be possible. Not only that, it uses an internal `require`
827
+ which is not `Kernel#require`.
828
+
829
+ Then, it provides no way to remove declarations in case a file is deleted. If a
830
+ constant gets removed with `Module#remove_const` its `autoload` is not triggered
831
+ again. Also, it doesn't support qualified names, so files with namespaces should
832
+ be interpreted during the walk tree to install their own `autoload` calls, but
833
+ those files could have constant references not yet configured.
834
+
835
+ An implementation based on `Module#autoload` would be awesome but, as you see,
836
+ at least as of today it is not possible. Constant autoloading in Rails is
837
+ implemented with `Module#const_missing`, and that's why it has its own contract,
838
+ documented in this guide.
839
+
840
+
841
+ Common Gotchas
842
+ --------------
843
+
844
+ ### Nesting and Qualified Constants
845
+
846
+ Let's consider
847
+
848
+ ```ruby
849
+ module Admin
850
+ class UsersController < ApplicationController
851
+ def index
852
+ @users = User.all
853
+ end
854
+ end
855
+ end
856
+ ```
857
+
858
+ and
859
+
860
+ ```ruby
861
+ class Admin::UsersController < ApplicationController
862
+ def index
863
+ @users = User.all
864
+ end
865
+ end
866
+ ```
867
+
868
+ To resolve `User` Ruby checks `Admin` in the former case, but it does not in
869
+ the latter because it does not belong to the nesting. (See [Nesting](#nesting)
870
+ and [Resolution Algorithms](#resolution-algorithms).)
871
+
872
+ Unfortunately Rails autoloading does not know the nesting in the spot where the
873
+ constant was missing and so it is not able to act as Ruby would. In particular,
874
+ `Admin::User` will get autoloaded in either case.
875
+
876
+ Albeit qualified constants with `class` and `module` keywords may technically
877
+ work with autoloading in some cases, it is preferable to use relative constants
878
+ instead:
879
+
880
+ ```ruby
881
+ module Admin
882
+ class UsersController < ApplicationController
883
+ def index
884
+ @users = User.all
885
+ end
886
+ end
887
+ end
888
+ ```
889
+
890
+ ### Autoloading and STI
891
+
892
+ Single Table Inheritance (STI) is a feature of Active Record that easies
893
+ storing a hierarchy of models in one single table. The API of such models is
894
+ aware of the hierarchy and encapsulates some common needs. For example, given
895
+ these classes:
896
+
897
+ ```ruby
898
+ # app/models/polygon.rb
899
+ class Polygon < ActiveRecord::Base
900
+ end
901
+
902
+ # app/models/triangle.rb
903
+ class Triangle < Polygon
904
+ end
905
+
906
+ # app/models/rectangle.rb
907
+ class Rectangle < Polygon
908
+ end
909
+ ```
910
+
911
+ `Triangle.create` creates a row that represents a triangle, and
912
+ `Rectangle.create` creates a row that represents a rectangle. If `id` is the
913
+ ID of an existing record, `Polygon.find(id)` returns an object of the correct
914
+ type.
915
+
916
+ Methods that operate on collections are also aware of the hierarchy. For
917
+ example, `Polygon.all` returns all the records of the table, because all
918
+ rectangles and triangles are polygons. Active Record takes care of returning
919
+ instances of their corresponding class in the result set.
920
+
921
+ Types are autoloaded as needed. For example, if `Polygon.first` is a rectangle
922
+ and `Rectangle` has not yet been loaded, Active Record autoloads it and the
923
+ record is correctly instantiated.
924
+
925
+ All good, but if instead of performing queries based on the root class we need
926
+ to work on some subclass, things get interesting.
927
+
928
+ While working with `Polygon` you do not need to be aware of all its descendants,
929
+ because anything in the table is by definition a polygon, but when working with
930
+ subclasses Active Record needs to be able to enumerate the types it is looking
931
+ for. Let’s see an example.
932
+
933
+ `Rectangle.all` only loads rectangles by adding a type constraint to the query:
934
+
935
+ ```sql
936
+ SELECT "polygons".* FROM "polygons"
937
+ WHERE "polygons"."type" IN ("Rectangle")
938
+ ```
939
+
940
+ Let’s introduce now a subclass of `Rectangle`:
941
+
942
+ ```ruby
943
+ # app/models/square.rb
944
+ class Square < Rectangle
945
+ end
946
+ ```
947
+
948
+ `Rectangle.all` should now return rectangles **and** squares:
949
+
950
+ ```sql
951
+ SELECT "polygons".* FROM "polygons"
952
+ WHERE "polygons"."type" IN ("Rectangle", "Square")
953
+ ```
954
+
955
+ But there’s a caveat here: How does Active Record know that the class `Square`
956
+ exists at all?
957
+
958
+ Even if the file `app/models/square.rb` exists and defines the `Square` class,
959
+ if no code yet used that class, `Rectangle.all` issues the query
960
+
961
+ ```sql
962
+ SELECT "polygons".* FROM "polygons"
963
+ WHERE "polygons"."type" IN ("Rectangle")
964
+ ```
965
+
966
+ That is not a bug, the query includes all *known* descendants of `Rectangle`.
967
+
968
+ A way to ensure this works correctly regardless of the order of execution is to
969
+ load the leaves of the tree by hand at the bottom of the file that defines the
970
+ root class:
971
+
972
+ ```ruby
973
+ # app/models/polygon.rb
974
+ class Polygon < ActiveRecord::Base
975
+ end
976
+ require_dependency ‘square’
977
+ ```
978
+
979
+ Only the leaves that are **at least grandchildren** need to be loaded this
980
+ way. Direct subclasses do not need to be preloaded. If the hierarchy is
981
+ deeper, intermediate classes will be autoloaded recursively from the bottom
982
+ because their constant will appear in the class definitions as superclass.
983
+
984
+ ### Autoloading and `require`
985
+
986
+ Files defining constants to be autoloaded should never be `require`d:
987
+
988
+ ```ruby
989
+ require 'user' # DO NOT DO THIS
990
+
991
+ class UsersController < ApplicationController
992
+ ...
993
+ end
994
+ ```
995
+
996
+ There are two possible gotchas here in development mode:
997
+
998
+ 1. If `User` is autoloaded before reaching the `require`, `app/models/user.rb`
999
+ runs again because `load` does not update `$LOADED_FEATURES`.
1000
+
1001
+ 2. If the `require` runs first Rails does not mark `User` as an autoloaded
1002
+ constant and changes to `app/models/user.rb` aren't reloaded.
1003
+
1004
+ Just follow the flow and use constant autoloading always, never mix
1005
+ autoloading and `require`. As a last resort, if some file absolutely needs to
1006
+ load a certain file use `require_dependency` to play nice with constant
1007
+ autoloading. This option is rarely needed in practice, though.
1008
+
1009
+ Of course, using `require` in autoloaded files to load ordinary 3rd party
1010
+ libraries is fine, and Rails is able to distinguish their constants, they are
1011
+ not marked as autoloaded.
1012
+
1013
+ ### Autoloading and Initializers
1014
+
1015
+ Consider this assignment in `config/initializers/set_auth_service.rb`:
1016
+
1017
+ ```ruby
1018
+ AUTH_SERVICE = if Rails.env.production?
1019
+ RealAuthService
1020
+ else
1021
+ MockedAuthService
1022
+ end
1023
+ ```
1024
+
1025
+ The purpose of this setup would be that the application uses the class that
1026
+ corresponds to the environment via `AUTH_SERVICE`. In development mode
1027
+ `MockedAuthService` gets autoloaded when the initializer runs. Let’s suppose
1028
+ we do some requests, change its implementation, and hit the application again.
1029
+ To our surprise the changes are not reflected. Why?
1030
+
1031
+ As [we saw earlier](#constant-reloading), Rails removes autoloaded constants,
1032
+ but `AUTH_SERVICE` stores the original class object. Stale, non-reachable
1033
+ using the original constant, but perfectly functional.
1034
+
1035
+ The following code summarizes the situation:
1036
+
1037
+ ```ruby
1038
+ class C
1039
+ def quack
1040
+ 'quack!'
1041
+ end
1042
+ end
1043
+
1044
+ X = C
1045
+ Object.instance_eval { remove_const(:C) }
1046
+ X.new.quack # => quack!
1047
+ X.name # => C
1048
+ C # => uninitialized constant C (NameError)
1049
+ ```
1050
+
1051
+ Because of that, it is not a good idea to autoload constants on application
1052
+ initialization.
1053
+
1054
+ In the case above we could implement a dynamic access point:
1055
+
1056
+ ```ruby
1057
+ # app/models/auth_service.rb
1058
+ class AuthService
1059
+ if Rails.env.production?
1060
+ def self.instance
1061
+ RealAuthService
1062
+ end
1063
+ else
1064
+ def self.instance
1065
+ MockedAuthService
1066
+ end
1067
+ end
1068
+ end
1069
+ ```
1070
+
1071
+ and have the application use `AuthService.instance` instead. `AuthService`
1072
+ would be loaded on demand and be autoload-friendly.
1073
+
1074
+ ### `require_dependency` and Initializers
1075
+
1076
+ As we saw before, `require_dependency` loads files in an autoloading-friendly
1077
+ way. Normally, though, such a call does not make sense in an initializer.
1078
+
1079
+ One could think about doing some [`require_dependency`](#require-dependency)
1080
+ calls in an initializer to make sure certain constants are loaded upfront, for
1081
+ example as an attempt to address the [gotcha with STIs](#autoloading-and-sti).
1082
+
1083
+ Problem is, in development mode [autoloaded constants are wiped](#constant-reloading)
1084
+ if there is any relevant change in the file system. If that happens then
1085
+ we are in the very same situation the initializer wanted to avoid!
1086
+
1087
+ Calls to `require_dependency` have to be strategically written in autoloaded
1088
+ spots.
1089
+
1090
+ ### When Constants aren't Missed
1091
+
1092
+ #### Relative References
1093
+
1094
+ Let's consider a flight simulator. The application has a default flight model
1095
+
1096
+ ```ruby
1097
+ # app/models/flight_model.rb
1098
+ class FlightModel
1099
+ end
1100
+ ```
1101
+
1102
+ that can be overridden by each airplane, for instance
1103
+
1104
+ ```ruby
1105
+ # app/models/bell_x1/flight_model.rb
1106
+ module BellX1
1107
+ class FlightModel < FlightModel
1108
+ end
1109
+ end
1110
+
1111
+ # app/models/bell_x1/aircraft.rb
1112
+ module BellX1
1113
+ class Aircraft
1114
+ def initialize
1115
+ @flight_model = FlightModel.new
1116
+ end
1117
+ end
1118
+ end
1119
+ ```
1120
+
1121
+ The initializer wants to create a `BellX1::FlightModel` and nesting has
1122
+ `BellX1`, that looks good. But if the default flight model is loaded and the
1123
+ one for the Bell-X1 is not, the interpreter is able to resolve the top-level
1124
+ `FlightModel` and autoloading is thus not triggered for `BellX1::FlightModel`.
1125
+
1126
+ That code depends on the execution path.
1127
+
1128
+ These kind of ambiguities can often be resolved using qualified constants:
1129
+
1130
+ ```ruby
1131
+ module BellX1
1132
+ class Plane
1133
+ def flight_model
1134
+ @flight_model ||= BellX1::FlightModel.new
1135
+ end
1136
+ end
1137
+ end
1138
+ ```
1139
+
1140
+ Also, `require_dependency` is a solution:
1141
+
1142
+ ```ruby
1143
+ require_dependency 'bell_x1/flight_model'
1144
+
1145
+ module BellX1
1146
+ class Plane
1147
+ def flight_model
1148
+ @flight_model ||= FlightModel.new
1149
+ end
1150
+ end
1151
+ end
1152
+ ```
1153
+
1154
+ #### Qualified References
1155
+
1156
+ Given
1157
+
1158
+ ```ruby
1159
+ # app/models/hotel.rb
1160
+ class Hotel
1161
+ end
1162
+
1163
+ # app/models/image.rb
1164
+ class Image
1165
+ end
1166
+
1167
+ # app/models/hotel/image.rb
1168
+ class Hotel
1169
+ class Image < Image
1170
+ end
1171
+ end
1172
+ ```
1173
+
1174
+ the expression `Hotel::Image` is ambiguous, depends on the execution path.
1175
+
1176
+ As [we saw before](#resolution-algorithm-for-qualified-constants), Ruby looks
1177
+ up the constant in `Hotel` and its ancestors. If `app/models/image.rb` has
1178
+ been loaded but `app/models/hotel/image.rb` hasn't, Ruby does not find `Image`
1179
+ in `Hotel`, but it does in `Object`:
1180
+
1181
+ ```
1182
+ $ bin/rails r 'Image; p Hotel::Image' 2>/dev/null
1183
+ Image # NOT Hotel::Image!
1184
+ ```
1185
+
1186
+ The code evaluating `Hotel::Image` needs to make sure
1187
+ `app/models/hotel/image.rb` has been loaded, possibly with
1188
+ `require_dependency`.
1189
+
1190
+ In these cases the interpreter issues a warning though:
1191
+
1192
+ ```
1193
+ warning: toplevel constant Image referenced by Hotel::Image
1194
+ ```
1195
+
1196
+ This surprising constant resolution can be observed with any qualifying class:
1197
+
1198
+ ```
1199
+ 2.1.5 :001 > String::Array
1200
+ (irb):1: warning: toplevel constant Array referenced by String::Array
1201
+ => Array
1202
+ ```
1203
+
1204
+ WARNING. To find this gotcha the qualifying namespace has to be a class,
1205
+ `Object` is not an ancestor of modules.
1206
+
1207
+ ### Autoloading within Singleton Classes
1208
+
1209
+ Let's suppose we have these class definitions:
1210
+
1211
+ ```ruby
1212
+ # app/models/hotel/services.rb
1213
+ module Hotel
1214
+ class Services
1215
+ end
1216
+ end
1217
+
1218
+ # app/models/hotel/geo_location.rb
1219
+ module Hotel
1220
+ class GeoLocation
1221
+ class << self
1222
+ Services
1223
+ end
1224
+ end
1225
+ end
1226
+ ```
1227
+
1228
+ If `Hotel::Services` is known by the time `app/models/hotel/geo_location.rb`
1229
+ is being loaded, `Services` is resolved by Ruby because `Hotel` belongs to the
1230
+ nesting when the singleton class of `Hotel::GeoLocation` is opened.
1231
+
1232
+ But if `Hotel::Services` is not known, Rails is not able to autoload it, the
1233
+ application raises `NameError`.
1234
+
1235
+ The reason is that autoloading is triggered for the singleton class, which is
1236
+ anonymous, and as [we saw before](#generic-procedure), Rails only checks the
1237
+ top-level namespace in that edge case.
1238
+
1239
+ An easy solution to this caveat is to qualify the constant:
1240
+
1241
+ ```ruby
1242
+ module Hotel
1243
+ class GeoLocation
1244
+ class << self
1245
+ Hotel::Services
1246
+ end
1247
+ end
1248
+ end
1249
+ ```
1250
+
1251
+ ### Autoloading in `BasicObject`
1252
+
1253
+ Direct descendants of `BasicObject` do not have `Object` among their ancestors
1254
+ and cannot resolve top-level constants:
1255
+
1256
+ ```ruby
1257
+ class C < BasicObject
1258
+ String # NameError: uninitialized constant C::String
1259
+ end
1260
+ ```
1261
+
1262
+ When autoloading is involved that plot has a twist. Let's consider:
1263
+
1264
+ ```ruby
1265
+ class C < BasicObject
1266
+ def user
1267
+ User # WRONG
1268
+ end
1269
+ end
1270
+ ```
1271
+
1272
+ Since Rails checks the top-level namespace `User` gets autoloaded just fine the
1273
+ first time the `user` method is invoked. You only get the exception if the
1274
+ `User` constant is known at that point, in particular in a *second* call to
1275
+ `user`:
1276
+
1277
+ ```ruby
1278
+ c = C.new
1279
+ c.user # surprisingly fine, User
1280
+ c.user # NameError: uninitialized constant C::User
1281
+ ```
1282
+
1283
+ because it detects a parent namespace already has the constant (see [Qualified
1284
+ References](#qualified-references).)
1285
+
1286
+ As with pure Ruby, within the body of a direct descendant of `BasicObject` use
1287
+ always absolute constant paths:
1288
+
1289
+ ```ruby
1290
+ class C < BasicObject
1291
+ ::String # RIGHT
1292
+
1293
+ def user
1294
+ ::User # RIGHT
1295
+ end
1296
+ end
1297
+ ```