Class: Nanoc::Opal::Filter

Inherits:
Filter
  • Object
show all
Defined in:
lib/nanoc/opal/filter.rb

Instance Method Summary collapse

Instance Method Details

#run(string, params = {}) ⇒ String

Runs the content through [Opal](opalrb.com). Parameters passed as ‘:args` will be passed on to Opal..

Parameters:

  • content (String)

    The content to filter

Returns:

  • (String)

    The filtered content



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/nanoc/opal/filter.rb', line 14

def run(string, params = {})
  params = params.dup

  # Add current directory to the load path or something else if `load_path`
  # param is provided.
  ident = item.identifier.to_s
  fn = item.raw_filename
  dirname = File.dirname(fn)
  paths = params.delete(:load_path) || [dirname]
  paths = ::Opal.paths + paths
  params[:path_reader] = ::Opal::PathReader.new(
    paths,
    ::Opal::Builder.extensions.map { |e| [".#{e}", ".js.#{e}"] }.flatten
  )

  builder = ::Opal::Builder.new(**params)
  builder.build_str(string, fn)
  code = builder.to_s + "\n" + builder.source_map.to_data_uri_comment

  prefix = File.dirname(item.identifier.to_s)
  prefix += '/' unless prefix.end_with? '/'

  # Build a dependency chain
  dependencies = builder.dependent_files
  # Select only those required files that are present in our filesystem
  dependencies = dependencies.select { |i| i.start_with?(dirname) }
  # Remove the directory part up to a location of our asset
  dependencies = dependencies.map { |i| i.gsub(/\A#{dirname}\//, '') }
  # Add a prefix of our main asset (eg. /assets/js/)
  dependencies = dependencies.map { |i| prefix + i }
  # Convert that to Nanoc items
  dependencies = dependencies.map { |i| items[i] }.compact
  # Reject itself
  dependencies = dependencies.reject { |i| i == item }

  depend_on dependencies

  code
end