rails 4.2.1 → 5.1.7

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