在 rails 3.2 中仅在需要时自动加载 gem?
Autoload a gem only when needed in rails 3.2?
我正在尝试弄清楚如何仅在需要时加载特定的 gem。场景如下:
我正在使用很棒的 axlsx
gem 创建 Excel 文件。只有当用户请求 Excel 文件时,我的应用程序中允许此功能的功能才会被调用:
# model
require 'axlsx'
class AssessmentRaw < ActiveRecord::Base
# fun stuff here
def create_excel_file_io
xls = Axlsx::Package.new
# fun stuff here too
end
end
# a call in a controller
@assessment_raw_instance.create_excel_file_io
使用 derailed
gem 我可以看到 axlsx
占用大量内存:
axlsx: 9.8516 MiB (Also required by: /path-to-rails/app/models/assessment_raw)
axlsx/workbook/workbook.rb: 3.5391 MiB
axlsx/workbook/worksheet/worksheet.rb: 0.3477 MiB
axlsx/drawing/drawing.rb: 1.8438 MiB
zip: 1.6797 MiB
zip/entry: 0.3047 MiB
axlsx/stylesheet/styles.rb: 0.8516 MiB
htmlentities: 0.5273 MiB
htmlentities/flavors: 0.4453 MiB
htmlentities/mappings/expanded: 0.4258 MiB
axlsx/util/simple_typed_list.rb: 0.4727 MiB
所以我想知道... rails/ruby 是否允许 gem 延迟加载?
希望我说得够清楚了。 :-)
谢谢!
在 Gemfile 中:
gem 'axlsx', :require => false
模型中:
require 'axlsx'
我正在尝试弄清楚如何仅在需要时加载特定的 gem。场景如下:
我正在使用很棒的 axlsx
gem 创建 Excel 文件。只有当用户请求 Excel 文件时,我的应用程序中允许此功能的功能才会被调用:
# model
require 'axlsx'
class AssessmentRaw < ActiveRecord::Base
# fun stuff here
def create_excel_file_io
xls = Axlsx::Package.new
# fun stuff here too
end
end
# a call in a controller
@assessment_raw_instance.create_excel_file_io
使用 derailed
gem 我可以看到 axlsx
占用大量内存:
axlsx: 9.8516 MiB (Also required by: /path-to-rails/app/models/assessment_raw)
axlsx/workbook/workbook.rb: 3.5391 MiB
axlsx/workbook/worksheet/worksheet.rb: 0.3477 MiB
axlsx/drawing/drawing.rb: 1.8438 MiB
zip: 1.6797 MiB
zip/entry: 0.3047 MiB
axlsx/stylesheet/styles.rb: 0.8516 MiB
htmlentities: 0.5273 MiB
htmlentities/flavors: 0.4453 MiB
htmlentities/mappings/expanded: 0.4258 MiB
axlsx/util/simple_typed_list.rb: 0.4727 MiB
所以我想知道... rails/ruby 是否允许 gem 延迟加载?
希望我说得够清楚了。 :-) 谢谢!
在 Gemfile 中:
gem 'axlsx', :require => false
模型中:
require 'axlsx'