rails 4.1.16 → 4.2.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (143) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +12 -10
  3. data/guides/CHANGELOG.md +15 -100
  4. data/guides/Rakefile +5 -3
  5. data/guides/assets/javascripts/guides.js +6 -0
  6. data/guides/assets/stylesheets/main.css +4 -1
  7. data/guides/bug_report_templates/action_controller_master.rb +1 -0
  8. data/guides/rails_guides/helpers.rb +1 -1
  9. data/guides/rails_guides/levenshtein.rb +29 -21
  10. data/guides/rails_guides/markdown/renderer.rb +1 -1
  11. data/guides/rails_guides/markdown.rb +11 -7
  12. data/guides/rails_guides.rb +2 -2
  13. data/guides/source/2_2_release_notes.md +1 -1
  14. data/guides/source/2_3_release_notes.md +4 -4
  15. data/guides/source/3_0_release_notes.md +8 -8
  16. data/guides/source/3_1_release_notes.md +6 -3
  17. data/guides/source/3_2_release_notes.md +6 -3
  18. data/guides/source/4_0_release_notes.md +6 -3
  19. data/guides/source/4_1_release_notes.md +5 -6
  20. data/guides/source/4_2_release_notes.md +850 -0
  21. data/guides/source/_license.html.erb +1 -1
  22. data/guides/source/_welcome.html.erb +2 -8
  23. data/guides/source/action_controller_overview.md +81 -7
  24. data/guides/source/action_mailer_basics.md +91 -28
  25. data/guides/source/action_view_overview.md +148 -130
  26. data/guides/source/active_job_basics.md +318 -0
  27. data/guides/source/active_model_basics.md +371 -17
  28. data/guides/source/active_record_basics.md +19 -18
  29. data/guides/source/active_record_callbacks.md +12 -9
  30. data/guides/source/{migrations.md → active_record_migrations.md} +95 -220
  31. data/guides/source/active_record_postgresql.md +433 -0
  32. data/guides/source/active_record_querying.md +263 -265
  33. data/guides/source/active_record_validations.md +20 -11
  34. data/guides/source/active_support_core_extensions.md +159 -72
  35. data/guides/source/active_support_instrumentation.md +10 -7
  36. data/guides/source/api_documentation_guidelines.md +62 -16
  37. data/guides/source/asset_pipeline.md +258 -63
  38. data/guides/source/association_basics.md +81 -74
  39. data/guides/source/caching_with_rails.md +32 -7
  40. data/guides/source/command_line.md +52 -30
  41. data/guides/source/configuring.md +132 -29
  42. data/guides/source/constant_autoloading_and_reloading.md +1297 -0
  43. data/guides/source/contributing_to_ruby_on_rails.md +192 -112
  44. data/guides/source/credits.html.erb +2 -2
  45. data/guides/source/debugging_rails_applications.md +440 -286
  46. data/guides/source/development_dependencies_install.md +47 -36
  47. data/guides/source/documents.yaml +19 -7
  48. data/guides/source/engines.md +182 -182
  49. data/guides/source/form_helpers.md +79 -56
  50. data/guides/source/generators.md +24 -11
  51. data/guides/source/getting_started.md +337 -198
  52. data/guides/source/i18n.md +108 -65
  53. data/guides/source/index.html.erb +1 -0
  54. data/guides/source/initialization.md +108 -61
  55. data/guides/source/layout.html.erb +1 -4
  56. data/guides/source/layouts_and_rendering.md +27 -25
  57. data/guides/source/maintenance_policy.md +6 -3
  58. data/guides/source/nested_model_forms.md +7 -4
  59. data/guides/source/plugins.md +27 -27
  60. data/guides/source/rails_application_templates.md +21 -3
  61. data/guides/source/rails_on_rack.md +8 -4
  62. data/guides/source/routing.md +98 -72
  63. data/guides/source/ruby_on_rails_guides_guidelines.md +11 -12
  64. data/guides/source/security.md +38 -32
  65. data/guides/source/testing.md +188 -117
  66. data/guides/source/upgrading_ruby_on_rails.md +254 -28
  67. data/guides/source/working_with_javascript_in_rails.md +18 -16
  68. data/guides/w3c_validator.rb +2 -0
  69. metadata +40 -96
  70. data/guides/bug_report_templates/generic_gem.rb +0 -15
  71. data/guides/bug_report_templates/generic_master.rb +0 -26
  72. data/guides/code/getting_started/Gemfile +0 -40
  73. data/guides/code/getting_started/Gemfile.lock +0 -125
  74. data/guides/code/getting_started/README.rdoc +0 -28
  75. data/guides/code/getting_started/Rakefile +0 -6
  76. data/guides/code/getting_started/app/assets/javascripts/application.js +0 -15
  77. data/guides/code/getting_started/app/assets/javascripts/comments.js.coffee +0 -3
  78. data/guides/code/getting_started/app/assets/javascripts/posts.js.coffee +0 -3
  79. data/guides/code/getting_started/app/assets/javascripts/welcome.js.coffee +0 -3
  80. data/guides/code/getting_started/app/assets/stylesheets/application.css +0 -13
  81. data/guides/code/getting_started/app/assets/stylesheets/comments.css.scss +0 -3
  82. data/guides/code/getting_started/app/assets/stylesheets/posts.css.scss +0 -3
  83. data/guides/code/getting_started/app/assets/stylesheets/welcome.css.scss +0 -3
  84. data/guides/code/getting_started/app/controllers/application_controller.rb +0 -5
  85. data/guides/code/getting_started/app/controllers/comments_controller.rb +0 -23
  86. data/guides/code/getting_started/app/controllers/posts_controller.rb +0 -53
  87. data/guides/code/getting_started/app/controllers/welcome_controller.rb +0 -4
  88. data/guides/code/getting_started/app/helpers/application_helper.rb +0 -2
  89. data/guides/code/getting_started/app/helpers/comments_helper.rb +0 -2
  90. data/guides/code/getting_started/app/helpers/posts_helper.rb +0 -2
  91. data/guides/code/getting_started/app/helpers/welcome_helper.rb +0 -2
  92. data/guides/code/getting_started/app/models/comment.rb +0 -3
  93. data/guides/code/getting_started/app/models/post.rb +0 -7
  94. data/guides/code/getting_started/app/views/comments/_comment.html.erb +0 -15
  95. data/guides/code/getting_started/app/views/comments/_form.html.erb +0 -13
  96. data/guides/code/getting_started/app/views/layouts/application.html.erb +0 -14
  97. data/guides/code/getting_started/app/views/posts/_form.html.erb +0 -27
  98. data/guides/code/getting_started/app/views/posts/edit.html.erb +0 -5
  99. data/guides/code/getting_started/app/views/posts/index.html.erb +0 -21
  100. data/guides/code/getting_started/app/views/posts/new.html.erb +0 -5
  101. data/guides/code/getting_started/app/views/posts/show.html.erb +0 -18
  102. data/guides/code/getting_started/app/views/welcome/index.html.erb +0 -4
  103. data/guides/code/getting_started/bin/bundle +0 -4
  104. data/guides/code/getting_started/bin/rails +0 -4
  105. data/guides/code/getting_started/bin/rake +0 -4
  106. data/guides/code/getting_started/config/application.rb +0 -18
  107. data/guides/code/getting_started/config/boot.rb +0 -4
  108. data/guides/code/getting_started/config/database.yml +0 -25
  109. data/guides/code/getting_started/config/environment.rb +0 -5
  110. data/guides/code/getting_started/config/environments/development.rb +0 -30
  111. data/guides/code/getting_started/config/environments/production.rb +0 -80
  112. data/guides/code/getting_started/config/environments/test.rb +0 -36
  113. data/guides/code/getting_started/config/initializers/backtrace_silencers.rb +0 -7
  114. data/guides/code/getting_started/config/initializers/filter_parameter_logging.rb +0 -4
  115. data/guides/code/getting_started/config/initializers/inflections.rb +0 -16
  116. data/guides/code/getting_started/config/initializers/locale.rb +0 -9
  117. data/guides/code/getting_started/config/initializers/mime_types.rb +0 -5
  118. data/guides/code/getting_started/config/initializers/secret_token.rb +0 -12
  119. data/guides/code/getting_started/config/initializers/session_store.rb +0 -3
  120. data/guides/code/getting_started/config/initializers/wrap_parameters.rb +0 -14
  121. data/guides/code/getting_started/config/locales/en.yml +0 -23
  122. data/guides/code/getting_started/config/routes.rb +0 -7
  123. data/guides/code/getting_started/config.ru +0 -4
  124. data/guides/code/getting_started/db/migrate/20130122042648_create_posts.rb +0 -10
  125. data/guides/code/getting_started/db/migrate/20130122045842_create_comments.rb +0 -11
  126. data/guides/code/getting_started/db/schema.rb +0 -33
  127. data/guides/code/getting_started/db/seeds.rb +0 -7
  128. data/guides/code/getting_started/public/404.html +0 -60
  129. data/guides/code/getting_started/public/422.html +0 -60
  130. data/guides/code/getting_started/public/500.html +0 -59
  131. data/guides/code/getting_started/public/favicon.ico +0 -0
  132. data/guides/code/getting_started/public/robots.txt +0 -5
  133. data/guides/code/getting_started/test/controllers/comments_controller_test.rb +0 -7
  134. data/guides/code/getting_started/test/controllers/posts_controller_test.rb +0 -7
  135. data/guides/code/getting_started/test/controllers/welcome_controller_test.rb +0 -9
  136. data/guides/code/getting_started/test/fixtures/comments.yml +0 -11
  137. data/guides/code/getting_started/test/fixtures/posts.yml +0 -9
  138. data/guides/code/getting_started/test/helpers/comments_helper_test.rb +0 -4
  139. data/guides/code/getting_started/test/helpers/posts_helper_test.rb +0 -4
  140. data/guides/code/getting_started/test/helpers/welcome_helper_test.rb +0 -4
  141. data/guides/code/getting_started/test/models/comment_test.rb +0 -7
  142. data/guides/code/getting_started/test/models/post_test.rb +0 -7
  143. data/guides/code/getting_started/test/test_helper.rb +0 -12
@@ -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
+ ```