mon*_*man 10 ruby ruby-on-rails activesupport autoload
我正在寻找active_support.rb尝试了解它使用的加载过程.它采用三种不同负荷方法:load_all!,autoload和require.为什么在同一个文件中使用三种不同的加载方式?
module ActiveSupport
def self.load_all!
[Dependencies, Deprecation, Gzip, MessageVerifier, Multibyte, SecureRandom, TimeWithZone]
end
autoload :BacktraceCleaner, 'active_support/backtrace_cleaner'
autoload :Base64, 'active_support/base64'
autoload :BasicObject, 'active_support/basic_object'
autoload :BufferedLogger, 'active_support/buffered_logger'
autoload :Cache, 'active_support/cache'
autoload :Callbacks, 'active_support/callbacks'
autoload :Deprecation, 'active_support/deprecation'
autoload :Duration, 'active_support/duration'
autoload :Gzip, 'active_support/gzip'
autoload :Inflector, 'active_support/inflector'
autoload :Memoizable, 'active_support/memoizable'
autoload :MessageEncryptor, 'active_support/message_encryptor'
autoload :MessageVerifier, 'active_support/message_verifier'
autoload :Multibyte, 'active_support/multibyte'
autoload :OptionMerger, 'active_support/option_merger'
autoload :OrderedHash, 'active_support/ordered_hash'
autoload :OrderedOptions, 'active_support/ordered_options'
autoload :Rescuable, 'active_support/rescuable'
autoload :SecureRandom, 'active_support/secure_random'
autoload :StringInquirer, 'active_support/string_inquirer'
autoload :TimeWithZone, 'active_support/time_with_zone'
autoload :TimeZone, 'active_support/values/time_zone'
autoload :XmlMini, 'active_support/xml_mini'
end
require 'active_support/vendor'
require 'active_support/core_ext'
require 'active_support/dependencies'
require 'active_support/json'
I18n.load_path << "#{File.dirname(__FILE__)}/active_support/locale/en.yml"
Run Code Online (Sandbox Code Playgroud)
Eri*_*rom 16
我不知道为什么Rails使用三种不同的加载方法(实际上是两种 - 见下文).但我知道,一般来说,为什么有人会这样做.
Require意思是"立即加载".autoload意思是"当你需要使用它时加载它".使用两者的通常原因是你有一些你几乎认为将在每个程序调用中使用的文件; 和其他可选的.例如,在不使用弃用方法的Rails应用程序中,您将永远不需要Deprecation; 那么为什么要通过加载该文件来减慢初始设置?
在其他情况下,您可以区分程序执行早期需要的文件和可以等待的文件.例如,Gzip在第一个请求进入之前您不太可能需要.因此,通过使用自动加载,您可以缩短初始设置的时间,但代价是第一个请求稍微减慢.
你可能会问,为什么不只是autoload用于一切?为什么在绝对需要之前加载任何东西?一个原因是自动加载仅适用于常量.因此,例如,active_support/core_ext增加了大量的方法来数值所以你可以写这样的代码3.days,6.minutes以及16.seconds.ago.没有常数3.days,因此您无法在该表达式上触发自动加载.(并且你不能自动加载Numeric,因为基类已经被加载 - 它只是你想要添加的扩展名.)
最后,这个类实际上并没有使用三种加载方法; 它使用两个,并提供一个(一种).load_all!所使用的Rails::Initializer以
Run Code Online (Sandbox Code Playgroud)# Preload all frameworks specified by the Configuration#frameworks. # Used by Passenger to ensure everything's loaded before forking and # to avoid autoload race conditions in JRuby.
我不知道细节,我不知道为什么这些特定模块被预加载(而不是其他模块).但由于这是为了支持特定环境,因此您可以看到为什么它可能需要与默认加载机制分开的代码.
| 归档时间: |
|
| 查看次数: |
2851 次 |
| 最近记录: |