Module: Opal::Sprockets

Defined in:
opal/lib/opal/sprockets.rb,
opal/lib/opal/sprockets/path_reader.rb,
opal/lib/opal/sprockets/source_map_header_patch.rb

Defined Under Namespace

Modules: Processor, SourceMapHeaderPatch Classes: PathReader

Class Method Summary collapse

Class Method Details

.javascript_include_tag(name, options = {}) ⇒ Object

Generate a <script> tag for Opal assets.

Parameters:

  • name (String)

    The logical name of the asset to be loaded (without extension)

  • options (Hash) (defaults to: {})

    The options about sprockets

Options Hash (options):

  • :sprockets (Sprockets::Environment)

    The sprockets instance

  • :prefix (String)

    The prefix String at which is mounted Sprockets, e.g. '/assets'

  • :debug (Boolean)

    Wether to enable debug mode along with sourcemaps support

Returns:

  • a string of HTML code containing <script> tags.



52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'opal/lib/opal/sprockets.rb', line 52

def self.javascript_include_tag(name, options = {})
  sprockets = options.fetch(:sprockets)
  prefix    = options.fetch(:prefix)
  debug     = options.fetch(:debug)

  # Avoid double slashes
  prefix = prefix.chop if prefix.end_with? '/'

  asset = sprockets[name]
  raise "Cannot find asset: #{name}" if asset.nil?
  scripts = []

  if debug
    asset.to_a.map do |dependency|
      scripts << %{<script src="#{prefix}/#{dependency.logical_path}?body=1"></script>}
    end
  else
    scripts << %{<script src="#{prefix}/#{name}.js"></script>}
  end

  scripts << %{<script>#{::Opal::Sprockets.load_asset(name)}</script>}

  scripts.join "\n"
end

.load_asset(name, _sprockets = :deprecated) ⇒ String

Bootstraps modules loaded by sprockets on Opal.modules marking any non-Opal asset as already loaded.

Examples:


Opal::Sprockets.load_asset('application')

Will output the following JavaScript:


if (typeof(Opal) !== 'undefined') {
  Opal.loaded("opal");
  Opal.loaded("jquery.self");
  Opal.load("application");
}

Parameters:

  • name (String)

    The logical name of the main asset to be loaded (without extension)

Returns:

  • (String)

    JavaScript code



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'opal/lib/opal/sprockets.rb', line 25

def self.load_asset(name, _sprockets = :deprecated)
  if _sprockets != :deprecated && !@load_asset_warning_displayed
    @load_asset_warning_displayed = true
    warn "Passing a sprockets environment to Opal::Sprockets.load_asset no more needed.\n  #{caller(1, 3).join("\n  ")}"
  end

  name = name.sub(/(\.(js|rb|opal))*\z/, '')
  stubbed_files     = ::Opal::Config.stubbed_files

  loaded = ['opal', 'corelib/runtime'] + stubbed_files.to_a

  "if (typeof(Opal) !== 'undefined') { "\
    "Opal.loaded(#{loaded.to_json}); "\
    "if (typeof(OpalLoaded) === 'undefined') Opal.loaded(OpalLoaded); "\
    "if (Opal.modules[#{name.to_json}]) Opal.load(#{name.to_json}); "\
  "}"
end