Class: Sprockets::Commoner::Bundle

Inherits:
Schmooze::Base
  • Object
show all
Defined in:
lib/sprockets/commoner/bundle.rb

Constant Summary collapse

InaccessibleStubbedFileError =
Class.new(::StandardError)
JS_PACKAGE_PATH =
File.expand_path('../../../js', __dir__)
PRELUDE =
"!function() {\nvar __commoner_initialize_module__ = function(f) {\n  var module = {exports: {}};\n  f.call(module.exports, module, module.exports);\n  return module.exports;\n};\nvar global = window;\n".freeze
OUTRO =
"}();\n".freeze

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(root) ⇒ Bundle

Returns a new instance of Bundle.



44
45
46
# File 'lib/sprockets/commoner/bundle.rb', line 44

def initialize(root)
  super(root, 'NODE_PATH' => JS_PACKAGE_PATH)
end

Class Method Details

.call(input) ⇒ Object



52
53
54
55
# File 'lib/sprockets/commoner/bundle.rb', line 52

def self.call(input)
  env = input[:environment]
  instance(env).call(input)
end

.instance(env) ⇒ Object



48
49
50
# File 'lib/sprockets/commoner/bundle.rb', line 48

def self.instance(env)
  @instance ||= new(env.root)
end

Instance Method Details

#call(input) ⇒ Object



57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/sprockets/commoner/bundle.rb', line 57

def call(input)
  return unless input[:metadata][:commoner_enabled]
  env = input[:environment]
  # Get the filenames of all the assets that are included in the bundle
  assets_in_bundle = Set.new(input[:metadata][:included]) { |uri| env.load(uri).filename }
  # Subtract the assets in the bundle from those that are required. The missing assets were excluded through stubbing.
  assets_missing = input[:metadata][:commoner_required] - assets_in_bundle

  global_identifiers = assets_missing.map do |filename|
    uri, _ = if Sprockets::VERSION < '4'
      env.resolve(filename, accept: input[:content_type], pipeline: :self, compat: false)
    else
      env.resolve(filename, accept: input[:content_type], pipeline: :self)
    end
    asset = env.load(uri)
    # Retrieve the global variable the file is exposed through
    global = asset.[:commoner_global_identifier]
    raise InaccessibleStubbedFileError, "#{filename} is stubbed in #{input[:filename]} but doesn't define a global. Add an 'expose' directive." if global.nil?
    [filename.slice(env.root.size + 1, filename.size), global]
  end

  used_helpers = input[:metadata][:commoner_used_helpers].to_a
  header_code = generate_header(used_helpers, global_identifiers)
  {
    data: "#{PRELUDE}#{header_code}\n#{input[:data]}#{OUTRO}"
  }
end