mercredi 27 avril 2016

Autoload a gem only when needed in rails 3.2?

I'm trying to figure out how to load a specific gem only when needed. Here the scenario:

I'm using the great axlsx gem to create Excel files. The feature in my app allowing this is called only when the user ask for a Excel file:

# 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

Using derailed gem I can see that axlsx is heavy on memory:

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

So I wonder... if rails/ruby allow lazy loading for a gem?

Hope I'm clear enough. :-) Thank you!

Aucun commentaire:

Enregistrer un commentaire