Class: Sprockets::DirectiveProcessor

Inherits:
Object
  • Object
show all
Defined in:
lib/sprockets/directive_processor.rb

Overview

The ‘DirectiveProcessor` is responsible for parsing and evaluating directive comments in a source file.

A directive comment starts with a comment prefix, followed by an “=”, then the directive name, then any arguments.

// JavaScript
//= require "foo"

# CoffeeScript
#= require "bar"

/* CSS
 *= require "baz"
 */

This makes it possible to disable or modify the processor to do whatever you’d like. You could add your own custom directives or invent your own directive syntax.

‘Environment#processors` includes `DirectiveProcessor` by default.

To remove the processor entirely:

env.unregister_processor('text/css', Sprockets::DirectiveProcessor)
env.unregister_processor('application/javascript', Sprockets::DirectiveProcessor)

Then inject your own preprocessor:

env.register_processor('text/css', MyProcessor)

Constant Summary collapse

VERSION =
'1'
DIRECTIVE_PATTERN =

Directives are denoted by a ‘=` followed by the name, then argument list.

A few different styles are allowed:

// =require foo
//= require foo
//= require "foo"
/
  ^ \W* = \s* (\w+.*?) (\*\/)? $
/x

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ DirectiveProcessor

Returns a new instance of DirectiveProcessor.



63
64
65
# File 'lib/sprockets/directive_processor.rb', line 63

def initialize(options = {})
  @header_pattern = compile_header_pattern(Array(options[:comments]))
end

Class Method Details

.call(input) ⇒ Object



59
60
61
# File 'lib/sprockets/directive_processor.rb', line 59

def self.call(input)
  instance.call(input)
end

.instanceObject



52
53
54
55
56
57
# File 'lib/sprockets/directive_processor.rb', line 52

def self.instance
  @instance ||= new(
    # Deprecated: Default to C and Ruby comment styles
    comments: ["//", ["/*", "*/"]] + ["#", ["###", "###"]]
  )
end

Instance Method Details

#_call(input) ⇒ Object



71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# File 'lib/sprockets/directive_processor.rb', line 71

def _call(input)
  @environment  = input[:environment]
  @uri          = input[:uri]
  @filename     = input[:filename]
  @dirname      = File.dirname(@filename)
  @content_type = input[:content_type]
  @required     = Set.new(input[:metadata][:required])
  @stubbed      = Set.new(input[:metadata][:stubbed])
  @links        = Set.new(input[:metadata][:links])
  @dependencies = Set.new(input[:metadata][:dependencies])

  data, directives = process_source(input[:data])
  process_directives(directives)

  { data: data,
    required: @required,
    stubbed: @stubbed,
    links: @links,
    dependencies: @dependencies }
end

#call(input) ⇒ Object



67
68
69
# File 'lib/sprockets/directive_processor.rb', line 67

def call(input)
  dup._call(input)
end