rails 3.2.22.2 → 4.2.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (216) hide show
  1. checksums.yaml +7 -0
  2. data/README.md +85 -0
  3. data/guides/CHANGELOG.md +31 -0
  4. data/guides/Rakefile +79 -0
  5. data/guides/assets/images/akshaysurve.jpg +0 -0
  6. data/guides/assets/images/belongs_to.png +0 -0
  7. data/guides/assets/images/book_icon.gif +0 -0
  8. data/guides/assets/images/bullet.gif +0 -0
  9. data/guides/assets/images/chapters_icon.gif +0 -0
  10. data/guides/assets/images/check_bullet.gif +0 -0
  11. data/guides/assets/images/credits_pic_blank.gif +0 -0
  12. data/guides/assets/images/csrf.png +0 -0
  13. data/guides/assets/images/edge_badge.png +0 -0
  14. data/guides/assets/images/favicon.ico +0 -0
  15. data/guides/assets/images/feature_tile.gif +0 -0
  16. data/guides/assets/images/footer_tile.gif +0 -0
  17. data/guides/assets/images/fxn.png +0 -0
  18. data/guides/assets/images/getting_started/article_with_comments.png +0 -0
  19. data/guides/assets/images/getting_started/challenge.png +0 -0
  20. data/guides/assets/images/getting_started/confirm_dialog.png +0 -0
  21. data/guides/assets/images/getting_started/forbidden_attributes_for_new_article.png +0 -0
  22. data/guides/assets/images/getting_started/form_with_errors.png +0 -0
  23. data/guides/assets/images/getting_started/index_action_with_edit_link.png +0 -0
  24. data/guides/assets/images/getting_started/new_article.png +0 -0
  25. data/guides/assets/images/getting_started/rails_welcome.png +0 -0
  26. data/guides/assets/images/getting_started/routing_error_no_controller.png +0 -0
  27. data/guides/assets/images/getting_started/routing_error_no_route_matches.png +0 -0
  28. data/guides/assets/images/getting_started/show_action_for_articles.png +0 -0
  29. data/guides/assets/images/getting_started/template_is_missing_articles_new.png +0 -0
  30. data/guides/assets/images/getting_started/unknown_action_create_for_articles.png +0 -0
  31. data/guides/assets/images/getting_started/unknown_action_new_for_articles.png +0 -0
  32. data/guides/assets/images/grey_bullet.gif +0 -0
  33. data/guides/assets/images/habtm.png +0 -0
  34. data/guides/assets/images/has_many.png +0 -0
  35. data/guides/assets/images/has_many_through.png +0 -0
  36. data/guides/assets/images/has_one.png +0 -0
  37. data/guides/assets/images/has_one_through.png +0 -0
  38. data/guides/assets/images/header_backdrop.png +0 -0
  39. data/guides/assets/images/header_tile.gif +0 -0
  40. data/guides/assets/images/i18n/demo_html_safe.png +0 -0
  41. data/guides/assets/images/i18n/demo_localized_pirate.png +0 -0
  42. data/guides/assets/images/i18n/demo_translated_en.png +0 -0
  43. data/guides/assets/images/i18n/demo_translated_pirate.png +0 -0
  44. data/guides/assets/images/i18n/demo_translation_missing.png +0 -0
  45. data/guides/assets/images/i18n/demo_untranslated.png +0 -0
  46. data/guides/assets/images/icons/README +5 -0
  47. data/guides/assets/images/icons/callouts/1.png +0 -0
  48. data/guides/assets/images/icons/callouts/10.png +0 -0
  49. data/guides/assets/images/icons/callouts/11.png +0 -0
  50. data/guides/assets/images/icons/callouts/12.png +0 -0
  51. data/guides/assets/images/icons/callouts/13.png +0 -0
  52. data/guides/assets/images/icons/callouts/14.png +0 -0
  53. data/guides/assets/images/icons/callouts/15.png +0 -0
  54. data/guides/assets/images/icons/callouts/2.png +0 -0
  55. data/guides/assets/images/icons/callouts/3.png +0 -0
  56. data/guides/assets/images/icons/callouts/4.png +0 -0
  57. data/guides/assets/images/icons/callouts/5.png +0 -0
  58. data/guides/assets/images/icons/callouts/6.png +0 -0
  59. data/guides/assets/images/icons/callouts/7.png +0 -0
  60. data/guides/assets/images/icons/callouts/8.png +0 -0
  61. data/guides/assets/images/icons/callouts/9.png +0 -0
  62. data/guides/assets/images/icons/caution.png +0 -0
  63. data/guides/assets/images/icons/example.png +0 -0
  64. data/guides/assets/images/icons/home.png +0 -0
  65. data/guides/assets/images/icons/important.png +0 -0
  66. data/guides/assets/images/icons/next.png +0 -0
  67. data/guides/assets/images/icons/note.png +0 -0
  68. data/guides/assets/images/icons/prev.png +0 -0
  69. data/guides/assets/images/icons/tip.png +0 -0
  70. data/guides/assets/images/icons/up.png +0 -0
  71. data/guides/assets/images/icons/warning.png +0 -0
  72. data/guides/assets/images/nav_arrow.gif +0 -0
  73. data/guides/assets/images/oscardelben.jpg +0 -0
  74. data/guides/assets/images/polymorphic.png +0 -0
  75. data/guides/assets/images/radar.png +0 -0
  76. data/guides/assets/images/rails4_features.png +0 -0
  77. data/guides/assets/images/rails_guides_kindle_cover.jpg +0 -0
  78. data/guides/assets/images/rails_guides_logo.gif +0 -0
  79. data/guides/assets/images/rails_logo_remix.gif +0 -0
  80. data/guides/assets/images/session_fixation.png +0 -0
  81. data/guides/assets/images/tab_grey.gif +0 -0
  82. data/guides/assets/images/tab_info.gif +0 -0
  83. data/guides/assets/images/tab_note.gif +0 -0
  84. data/guides/assets/images/tab_red.gif +0 -0
  85. data/guides/assets/images/tab_yellow.gif +0 -0
  86. data/guides/assets/images/tab_yellow.png +0 -0
  87. data/guides/assets/images/vijaydev.jpg +0 -0
  88. data/guides/assets/javascripts/guides.js +59 -0
  89. data/guides/assets/javascripts/jquery.min.js +4 -0
  90. data/guides/assets/javascripts/responsive-tables.js +43 -0
  91. data/guides/assets/javascripts/syntaxhighlighter/shBrushAS3.js +59 -0
  92. data/guides/assets/javascripts/syntaxhighlighter/shBrushAppleScript.js +75 -0
  93. data/guides/assets/javascripts/syntaxhighlighter/shBrushBash.js +59 -0
  94. data/guides/assets/javascripts/syntaxhighlighter/shBrushCSharp.js +65 -0
  95. data/guides/assets/javascripts/syntaxhighlighter/shBrushColdFusion.js +100 -0
  96. data/guides/assets/javascripts/syntaxhighlighter/shBrushCpp.js +97 -0
  97. data/guides/assets/javascripts/syntaxhighlighter/shBrushCss.js +91 -0
  98. data/guides/assets/javascripts/syntaxhighlighter/shBrushDelphi.js +55 -0
  99. data/guides/assets/javascripts/syntaxhighlighter/shBrushDiff.js +41 -0
  100. data/guides/assets/javascripts/syntaxhighlighter/shBrushErlang.js +52 -0
  101. data/guides/assets/javascripts/syntaxhighlighter/shBrushGroovy.js +67 -0
  102. data/guides/assets/javascripts/syntaxhighlighter/shBrushJScript.js +52 -0
  103. data/guides/assets/javascripts/syntaxhighlighter/shBrushJava.js +57 -0
  104. data/guides/assets/javascripts/syntaxhighlighter/shBrushJavaFX.js +58 -0
  105. data/guides/assets/javascripts/syntaxhighlighter/shBrushPerl.js +72 -0
  106. data/guides/assets/javascripts/syntaxhighlighter/shBrushPhp.js +88 -0
  107. data/guides/assets/javascripts/syntaxhighlighter/shBrushPlain.js +33 -0
  108. data/guides/assets/javascripts/syntaxhighlighter/shBrushPowerShell.js +74 -0
  109. data/guides/assets/javascripts/syntaxhighlighter/shBrushPython.js +64 -0
  110. data/guides/assets/javascripts/syntaxhighlighter/shBrushRuby.js +55 -0
  111. data/guides/assets/javascripts/syntaxhighlighter/shBrushSass.js +94 -0
  112. data/guides/assets/javascripts/syntaxhighlighter/shBrushScala.js +51 -0
  113. data/guides/assets/javascripts/syntaxhighlighter/shBrushSql.js +66 -0
  114. data/guides/assets/javascripts/syntaxhighlighter/shBrushVb.js +56 -0
  115. data/guides/assets/javascripts/syntaxhighlighter/shBrushXml.js +69 -0
  116. data/guides/assets/javascripts/syntaxhighlighter/shCore.js +17 -0
  117. data/guides/assets/stylesheets/fixes.css +16 -0
  118. data/guides/assets/stylesheets/kindle.css +11 -0
  119. data/guides/assets/stylesheets/main.css +713 -0
  120. data/guides/assets/stylesheets/print.css +52 -0
  121. data/guides/assets/stylesheets/reset.css +43 -0
  122. data/guides/assets/stylesheets/responsive-tables.css +50 -0
  123. data/guides/assets/stylesheets/style.css +13 -0
  124. data/guides/assets/stylesheets/syntaxhighlighter/shCore.css +226 -0
  125. data/guides/assets/stylesheets/syntaxhighlighter/shCoreDefault.css +328 -0
  126. data/guides/assets/stylesheets/syntaxhighlighter/shCoreDjango.css +331 -0
  127. data/guides/assets/stylesheets/syntaxhighlighter/shCoreEclipse.css +339 -0
  128. data/guides/assets/stylesheets/syntaxhighlighter/shCoreEmacs.css +324 -0
  129. data/guides/assets/stylesheets/syntaxhighlighter/shCoreFadeToGrey.css +328 -0
  130. data/guides/assets/stylesheets/syntaxhighlighter/shCoreMDUltra.css +324 -0
  131. data/guides/assets/stylesheets/syntaxhighlighter/shCoreMidnight.css +324 -0
  132. data/guides/assets/stylesheets/syntaxhighlighter/shCoreRDark.css +324 -0
  133. data/guides/assets/stylesheets/syntaxhighlighter/shThemeDefault.css +117 -0
  134. data/guides/assets/stylesheets/syntaxhighlighter/shThemeDjango.css +120 -0
  135. data/guides/assets/stylesheets/syntaxhighlighter/shThemeEclipse.css +128 -0
  136. data/guides/assets/stylesheets/syntaxhighlighter/shThemeEmacs.css +113 -0
  137. data/guides/assets/stylesheets/syntaxhighlighter/shThemeFadeToGrey.css +117 -0
  138. data/guides/assets/stylesheets/syntaxhighlighter/shThemeMDUltra.css +113 -0
  139. data/guides/assets/stylesheets/syntaxhighlighter/shThemeMidnight.css +113 -0
  140. data/guides/assets/stylesheets/syntaxhighlighter/shThemeRDark.css +113 -0
  141. data/guides/assets/stylesheets/syntaxhighlighter/shThemeRailsGuides.css +116 -0
  142. data/guides/bug_report_templates/action_controller_gem.rb +47 -0
  143. data/guides/bug_report_templates/action_controller_master.rb +54 -0
  144. data/guides/bug_report_templates/active_record_gem.rb +40 -0
  145. data/guides/bug_report_templates/active_record_master.rb +49 -0
  146. data/guides/rails_guides/generator.rb +248 -0
  147. data/guides/rails_guides/helpers.rb +53 -0
  148. data/guides/rails_guides/indexer.rb +68 -0
  149. data/guides/rails_guides/kindle.rb +119 -0
  150. data/guides/rails_guides/levenshtein.rb +39 -0
  151. data/guides/rails_guides/markdown/renderer.rb +82 -0
  152. data/guides/rails_guides/markdown.rb +167 -0
  153. data/guides/rails_guides.rb +63 -0
  154. data/guides/source/2_2_release_notes.md +435 -0
  155. data/guides/source/2_3_release_notes.md +621 -0
  156. data/guides/source/3_0_release_notes.md +611 -0
  157. data/guides/source/3_1_release_notes.md +559 -0
  158. data/guides/source/3_2_release_notes.md +568 -0
  159. data/guides/source/4_0_release_notes.md +279 -0
  160. data/guides/source/4_1_release_notes.md +730 -0
  161. data/guides/source/4_2_release_notes.md +850 -0
  162. data/guides/source/_license.html.erb +2 -0
  163. data/guides/source/_welcome.html.erb +19 -0
  164. data/guides/source/action_controller_overview.md +1249 -0
  165. data/guides/source/action_mailer_basics.md +752 -0
  166. data/guides/source/action_view_overview.md +1620 -0
  167. data/guides/source/active_job_basics.md +318 -0
  168. data/guides/source/active_model_basics.md +554 -0
  169. data/guides/source/active_record_basics.md +374 -0
  170. data/guides/source/active_record_callbacks.md +413 -0
  171. data/guides/source/active_record_migrations.md +1018 -0
  172. data/guides/source/active_record_postgresql.md +433 -0
  173. data/guides/source/active_record_querying.md +1783 -0
  174. data/guides/source/active_record_validations.md +1178 -0
  175. data/guides/source/active_support_core_extensions.md +3904 -0
  176. data/guides/source/active_support_instrumentation.md +499 -0
  177. data/guides/source/api_documentation_guidelines.md +361 -0
  178. data/guides/source/asset_pipeline.md +1360 -0
  179. data/guides/source/association_basics.md +2236 -0
  180. data/guides/source/caching_with_rails.md +379 -0
  181. data/guides/source/command_line.md +625 -0
  182. data/guides/source/configuring.md +1045 -0
  183. data/guides/source/constant_autoloading_and_reloading.md +1297 -0
  184. data/guides/source/contributing_to_ruby_on_rails.md +624 -0
  185. data/guides/source/credits.html.erb +80 -0
  186. data/guides/source/debugging_rails_applications.md +861 -0
  187. data/guides/source/development_dependencies_install.md +289 -0
  188. data/guides/source/documents.yaml +205 -0
  189. data/guides/source/engines.md +1412 -0
  190. data/guides/source/form_helpers.md +1024 -0
  191. data/guides/source/generators.md +676 -0
  192. data/guides/source/getting_started.md +2085 -0
  193. data/guides/source/i18n.md +1086 -0
  194. data/guides/source/index.html.erb +28 -0
  195. data/guides/source/initialization.md +704 -0
  196. data/guides/source/kindle/copyright.html.erb +1 -0
  197. data/guides/source/kindle/layout.html.erb +27 -0
  198. data/guides/source/kindle/rails_guides.opf.erb +52 -0
  199. data/guides/source/kindle/toc.html.erb +24 -0
  200. data/guides/source/kindle/toc.ncx.erb +64 -0
  201. data/guides/source/kindle/welcome.html.erb +5 -0
  202. data/guides/source/layout.html.erb +143 -0
  203. data/guides/source/layouts_and_rendering.md +1227 -0
  204. data/guides/source/maintenance_policy.md +78 -0
  205. data/guides/source/nested_model_forms.md +228 -0
  206. data/guides/source/plugins.md +444 -0
  207. data/guides/source/rails_application_templates.md +266 -0
  208. data/guides/source/rails_on_rack.md +336 -0
  209. data/guides/source/routing.md +1141 -0
  210. data/guides/source/ruby_on_rails_guides_guidelines.md +127 -0
  211. data/guides/source/security.md +1024 -0
  212. data/guides/source/testing.md +1123 -0
  213. data/guides/source/upgrading_ruby_on_rails.md +1154 -0
  214. data/guides/source/working_with_javascript_in_rails.md +407 -0
  215. data/guides/w3c_validator.rb +97 -0
  216. metadata +290 -44
@@ -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
+ ```