123456789_123456789_123456789_123456789_123456789_

Class: Sprockets::Base

Relationships & Source Files
Extension / Inclusion / Inheritance Descendants
Subclasses:
Super Chains via Extension / Inclusion / Inheritance
Instance Chain:
Inherits: Object
Defined in: lib/sprockets/base.rb

Overview

Base class for Environment and CachedEnvironment.

Constant Summary

SourceMapUtils - Included

BASE64_DIGITS, BASE64_VALUES, VLQ_BASE, VLQ_BASE_MASK, VLQ_BASE_SHIFT, VLQ_CONTINUATION_BIT

DigestUtils - Included

ADD_VALUE_TO_DIGEST, DIGEST_SIZES, HASH_ALGORITHMS

PathUtils - Included

SEPARATOR_PATTERN

Utils - Included

MODULE_INCLUDE_MUTEX, WHITESPACE_ORDINALS

ProcessorUtils - Included

VALID_METADATA_COMPOUND_TYPES, VALID_METADATA_COMPOUND_TYPES_HASH, VALID_METADATA_TYPES, VALID_METADATA_VALUE_TYPES, VALID_METADATA_VALUE_TYPES_HASH

Server - Included

ALLOWED_REQUEST_METHODS, VARY, X_CASCADE

Bower - Included

POSSIBLE_BOWER_JSONS

Instance Attribute Summary

Configuration - Included

#config, #config=,
#context_class

This class maybe mutated and mixed in with custom helpers.

#digest_class

Public: Returns a Digest implementation class.

#digest_class=

Deprecated: Assign a Digest implementation class.

#logger

Get and set Logger instance.

#version

The Environment#version is a custom value used for manually expiring all asset caches.

#version=

Assign an environment version.

Paths - Included

#root

Returns Environment root.

#root=

Internal: Change Environment root.

Exporting - Included

#export_concurrent

Public: Checks if concurrent exporting is allowed.

#export_concurrent=

Public: Enable or disable the concurrently exporting files.

Compressing - Included

#css_compressor

Return CSS compressor or nil if none is set.

#css_compressor=

Assign a compressor to run on text/css assets.

#gzip=

Public: Enable or disable the creation of Gzip files.

#gzip?

Public: Checks if Gzip is enabled.

#js_compressor

Return JS compressor or nil if none is set.

#js_compressor=

Assign a compressor to run on application/javascript assets.

#skip_gzip?

Public: Checks if Gzip is disabled.

Instance Method Summary

Npm - Included

#read_package_directives

Internal: Read package.json’s main and style directives.

#resolve_alternates

Internal: Override resolve_alternates to install package.json behavior.

Bower - Included

#read_bower_main

Internal: Read bower.json’s main directive.

#resolve_alternates

Internal: Override resolve_alternates to install bower.json behavior.

Loader - Included

#load

Public: Load Asset by Asset URI.

#asset_from_cache

Internal: Load asset hash from cache.

#compress_key_from_hash, #expand_key_from_hash,
#fetch_asset_from_dependency_cache

Internal: Retrieves an asset based on its digest.

#load_from_unloaded

Internal: Loads an asset and saves it to cache.

#resolve_dependencies

Internal: Resolve set of dependency URIs.

#store_asset

Internal: Save a given asset to the cache.

Resolve - Included

#resolve

Public: Find Asset URI for given a logical path by searching the environment’s load paths.

#resolve!

Public: Same as resolve() but raises a FileNotFound exception instead of nil if no assets are found.

Server - Included

#call

call implements the Rack 1.x specification which accepts an env Hash and returns a three item tuple with the status code, headers, and body.

#bad_request_response

Returns a 400 Forbidden response tuple.

#cache_headers,
#css_exception_response

Returns a CSS response that hides all elements on the page and displays the exception.

#escape_css_content

Escape special characters for use inside a CSS content(“…”) string.

#forbidden_request?,
#forbidden_response

Returns a 403 Forbidden response tuple.

#head_request?, #headers,
#javascript_exception_response

Returns a JavaScript response that re-throws a Ruby exception in the browser.

#method_not_allowed_response,
#not_found_response

Returns a 404 Not Found response tuple.

#not_modified_response

Returns a 304 Not Modified response tuple.

#ok_response

Returns a 200 OK response tuple.

#path_fingerprint

Gets ETag fingerprint.

#precondition_failed_response

Configuration - Included

Paths - Included

#append_path

Append a path to the paths list.

#clear_paths

Clear all paths and start fresh.

#each_file

Public: Iterate over every file under all load paths.

#paths

Returns an Array of path Strings.

#prepend_path

Prepend a path to the paths list.

Mime - Included

#mime_exts

Internal: Mapping of MIME extension Strings to MIME type Strings.

#mime_type_charset_detecter

Internal: Get detecter function for MIME type.

#mime_types

Public: Mapping of MIME type Strings to properties Hash.

#read_file

Public: Read file on disk with MIME type specific encoding.

#register_mime_type

Public: Register a new mime type.

Transformers - Included

#compose_transformers

Internal: Compose multiple transformer steps into a single processor function.

#expand_transform_accepts

Internal: Expand accept type list to include possible transformed types.

#register_transformer

Public: Register a transformer from and to a mime type.

#register_transformer_suffix

Internal: Register transformer for existing type adding a suffix.

#resolve_transform_type

Internal: Resolve target mime type that the source type should be transformed to.

#transformers

Public: Two level mapping of a source mime type to a target mime type.

#compose_transformer_list, #compute_transformers!

HTTPUtils - Included

#find_best_mime_type_match

Internal: Find the best qvalue match from an Array of available mime type options.

#find_best_q_match

Internal: Find the best qvalue match from an Array of available options.

#find_mime_type_matches

Internal: Find the all qvalue match from an Array of available mime type options.

#find_q_matches

Internal: Find all qvalue matches from an Array of available options.

#match_mime_type?

Public: Test mime type against mime range.

#match_mime_type_keys

Public: Return values from Hash where the key matches the mime type.

#parse_q_values

Internal: Parse Accept header quality values.

Processing - Included

#bundle_processors

Bundle Processors are ran on concatenated assets rather than individual files.

#pipelines,
#postprocessors

Postprocessors are ran after Preprocessors and Engine processors.

#preprocessors

Preprocessors are ran before Postprocessors and Engine processors.

#processors
#register_bundle_metadata_reducer

Public: Register bundle metadata reducer function.

#register_bundle_processor

Registers a new Bundle Processor klass for mime_type.

#register_pipeline

Registers a pipeline that will be called by call_processor method.

#register_postprocessor

Registers a new Postprocessor klass for mime_type.

#register_preprocessor

Registers a new Preprocessor klass for mime_type.

#register_processor
#unregister_bundle_processor

Remove Bundle Processor klass for mime_type.

#unregister_postprocessor

Remove Postprocessor klass for mime_type.

#unregister_preprocessor

Remove Preprocessor klass for mime_type.

#unregister_processor
#register_config_processor, #unregister_config_processor

ProcessorUtils - Included

#call_processor

Public: Invoke processor.

#call_processors

Public: Invoke list of processors in right to left order.

#compose_processors

Public: Compose processors in right to left order.

#processor_cache_key

Internal: Get processor defined cached key.

#processors_cache_keys

Internal: Get combined cache keys for set of processors.

#validate_processor_result!

Internal: Validate returned result of calling a processor pipeline and raise a friendly user error message.

Exporting - Included

#exporters

Exporters are ran on the assets:precompile task.

#register_exporter

Public: Registers a new Exporter klass for mime_type.

#unregister_exporter

Public: Remove Exporting processor klass for mime_type.

Compressing - Included

#compressors,
#register_compressor

Public: Register a new compressor klass at sym for mime_type.

Dependencies - Included

#add_dependency

Public: Add environmental dependency inherited by all assets.

#depend_on
#dependencies

Public: Default set of dependency URIs for assets.

#dependency_resolvers

Public: Mapping dependency schemes to resolver functions.

#register_dependency_resolver

Public: Register new dependency URI resolver.

#resolve_dependency

Internal: Resolve dependency URIs.

Utils - Included

#concat_javascript_sources

Internal: Accumulate asset source to buffer and append a trailing semicolon if necessary.

#dfs

Internal: Post-order Depth-First search algorithm.

#dfs_paths

Internal: Post-order Depth-First search algorithm that gathers all paths along the way.

#duplicable?

Internal: Check if object can safely be .dup’d.

#hash_reassoc

Internal: Duplicate and store key/value on new frozen hash.

#hash_reassoc1

Internal: Duplicate and store key/value on new frozen hash.

#module_include

Internal: Inject into target module for the duration of the block.

#string_end_with_semicolon?

Internal: Check if string has a trailing semicolon.

PathDependencyUtils - Included

#entries_with_dependencies

Internal: List directory entries and return a set of dependencies that would invalid the cached return result.

#stat_directory_with_dependencies

Internal: List directory filenames and associated Stats under a directory.

#stat_sorted_tree_with_dependencies

Internal: List directory filenames and associated Stats under an entire directory tree.

URIUtils - Included

#build_asset_uri

Internal: Build Asset URI.

#build_file_digest_uri

Internal: Build file-digest dependency URI.

#encode_uri_query_params

Internal: Serialize hash of params into query string.

#join_file_uri

Internal: Join file: URI component parts into String.

#join_uri

Internal: Join URI component parts into String.

#parse_asset_uri

Internal: Parse Asset URI.

#parse_file_digest_uri

Internal: Parse file-digest dependency URI.

#parse_uri_query_params

Internal: Parse query string into hash of params.

#split_file_uri

Internal: Parse file: URI into component parts.

#split_uri

Internal: Parse URI into component parts.

#valid_asset_uri?

Internal: Check if String is a valid Asset URI.

PathDigestUtils - Included

#file_digest

Internal: Compute digest for path.

#files_digest

Internal: Compute digest for a set of paths.

#stat_digest

Internal: Compute digest for file stat.

PathUtils - Included

#absolute_path?

On Windows, ALT_SEPARATOR is \ Delegate to Pathname since the logic gets complex.

#atomic_write

Public: Write to a file atomically.

#directory?

Public: Like File.directory?.

#entries

Public: A version of Dir.entries that filters out ‘.` files and ~ swap files.

#file?

Public: Like File.file?.

#find_matching_path_for_extensions

Internal: Match paths in a directory against available extensions.

#find_upwards

Internal: Find target basename checking upwards from path.

#join

Public: Joins path to base path.

#match_path_extname

Internal: Match path extnames against available extensions.

#path_extnames

Internal: Get path’s extensions.

#path_parents

Internal: Returns all parents for path.

#paths_split

Internal: Detect root path and base for file in a set of paths.

#relative_path?

Public: Check if path is explicitly relative.

#relative_path_from

Public: Get relative path from start to dest.

#set_pipeline

Public: Sets pipeline for path.

#split_subpath

Internal: Get relative path for root path and subpath.

#stat

Public: Like File.stat.

#stat_directory

Public: Stat all the files under a directory.

#stat_sorted_tree

Public: Recursive stat all the files under a directory in alphabetical order.

#stat_tree

Public: Recursive stat all the files under a directory.

DigestUtils - Included

#already_digested?

Internal: Checks an asset name for a valid digest.

#detect_digest_class

Internal: Detect digest class hash algorithm for digest bytes.

#digest

Internal: Generate a hexdigest for a nested JSON serializable object.

#digest_class

Internal: Default digest class.

#hexdigest

Internal: Generate a hexdigest for a nested JSON serializable object.

#hexdigest_integrity_uri

Public: Generate hash for use in the integrity attribute of an asset tag as per the subresource integrity specification.

#integrity_uri

Public: Generate hash for use in the integrity attribute of an asset tag as per the subresource integrity specification.

#pack_base64digest

Internal: Pack a binary digest to a base64 encoded string.

#pack_hexdigest

Internal: Pack a binary digest to a hex encoded string.

#pack_urlsafe_base64digest

Internal: Pack a binary digest to a urlsafe base64 encoded string.

#unpack_hexdigest

Internal: Unpack a hex encoded digest string into binary bytes.

#build_digest

SourceMapUtils - Included

#bsearch_mappings

Public: Search Array of mappings for closest offset.

#combine_source_maps

Public: Combine two separate source map transformations into a single mapping.

#compare_source_offsets

Public: Compare two source map offsets.

#concat_source_maps

Public: Concatenate two source maps.

#decode_source_map

Public: Decompress source map.

#decode_vlq_mappings

Public: Decode VLQ mappings and match up sources and symbol names.

#encode_source_map

Public: Compress source map.

#encode_vlq_mappings

Public: Encode mappings Hash into a VLQ encoded String.

#format_source_map

Public: Transpose source maps into a standard format.

#make_index_map

Public: Converts source map to index map.

#vlq_decode

Public: Decode a VLQ string.

#vlq_decode_mappings

Public: Decode a VLQ string into mapping numbers.

#vlq_encode

Public: Encode a list of numbers into a compact VLQ string.

#vlq_encode_mappings

Public: Encode a mapping array into a compact VLQ string.

Instance Attribute Details

#cache (rw)

Get persistent cache store

[ GitHub ]

  
# File 'lib/sprockets/base.rb', line 41

attr_reader :cache

#cache=(cache) (rw)

Set persistent cache store

The cache store must implement a pair of getters and setters. Either ‘get(key)`/`set(key, value)`, `[key]`/`=value`, `read(key)`/`write(key, value)`.

[ GitHub ]

  
# File 'lib/sprockets/base.rb', line 48

def cache=(cache)
  @cache = Cache.new(cache, logger)
end

Instance Method Details

#[](*args, **options)

Preferred #find_asset shorthand.

environment['application.js']
[ GitHub ]

  
# File 'lib/sprockets/base.rb', line 118

def [](*args, **options)
  find_asset(*args, **options)
end

#cached Also known as: #index

Return an CachedEnvironment. Must be implemented by the subclass.

[ GitHub ]

  
# File 'lib/sprockets/base.rb', line 53

def cached
  raise NotImplementedError
end

#compress_from_root(uri)

[ GitHub ]

  
# File 'lib/sprockets/base.rb', line 139

def compress_from_root(uri)
  URITar.new(uri, self).compress
end

#expand_from_root(uri)

[ GitHub ]

  
# File 'lib/sprockets/base.rb', line 143

def expand_from_root(uri)
  URITar.new(uri, self).expand
end

#file_digest(path)

Internal: Compute digest for path.

path - String filename or directory path.

Returns a String digest or nil.

[ GitHub ]

  
# File 'lib/sprockets/base.rb', line 63

def file_digest(path)
  if stat = self.stat(path)
    # Caveat: Digests are cached by the path's current mtime. Its possible
    # for a files contents to have changed and its mtime to have been
    # negligently reset thus appearing as if the file hasn't changed on
    # disk. Also, the mtime is only read to the nearest second. It's
    # also possible the file was updated more than once in a given second.
    key = UnloadedAsset.new(path, self).file_digest_key(stat.mtime.to_i)
    cache.fetch(key) do
      self.stat_digest(path, stat)
    end
  end
end

#find_all_linked_assets(*args) {|asset| ... }

Yields:

  • (asset)
[ GitHub ]

  
# File 'lib/sprockets/base.rb', line 85

def find_all_linked_assets(*args)
  return to_enum(__method__, *args) unless block_given?

  parent_asset = asset = find_asset(*args)
  return unless asset

  yield asset
  stack = asset.links.to_a
  linked_paths = {}

  while uri = stack.shift
    yield asset = load(uri)

    last_filename = linked_paths[asset.logical_path]
    if last_filename && last_filename != asset.filename
      raise DoubleLinkError.new(
        parent_filename: parent_asset.filename,
        last_filename:   last_filename,
        logical_path:    asset.logical_path,
        filename:        asset.filename
      )
    end
    linked_paths[asset.logical_path] = asset.filename
    stack = asset.links.to_a + stack
  end

  nil
end

#find_asset(*args, **options)

Find asset by logical path or expanded path.

[ GitHub ]

  
# File 'lib/sprockets/base.rb', line 78

def find_asset(*args, **options)
  uri, _ = resolve(*args, **options)
  if uri
    load(uri)
  end
end

#find_asset!(*args)

Find asset by logical path or expanded path.

If the asset is not found an error will be raised.

[ GitHub ]

  
# File 'lib/sprockets/base.rb', line 125

def find_asset!(*args)
  uri, _ = resolve!(*args)
  if uri
    load(uri)
  end
end

#index

Alias for #cached.

[ GitHub ]

  
# File 'lib/sprockets/base.rb', line 56

alias_method :index, :cached

#inspect

Pretty inspect

[ GitHub ]

  
# File 'lib/sprockets/base.rb', line 133

def inspect
  "#<#{self.class}:0x#{object_id.to_s(16)} " +
    "root=#{root.to_s.inspect}, " +
    "paths=#{paths.inspect}>"
end