### Example ES6 Asset in Sprockets
Source: https://github.com/rails/sprockets/blob/main/UPGRADING.md
An example of an ES6 file (`.es6` extension) demonstrating a simple arrow function. Sprockets 4 will automatically process and transpile this file using the configured Babel processor.
```es6
// app/assets/javascript/application.es6
var square = (n) => n * n
console.log(square);
```
--------------------------------
### Changelog: Example Entry Format for Sprockets
Source: https://github.com/rails/sprockets/blob/main/CONTRIBUTING.md
This snippet provides an example of how to format a new entry in the `CHANGELOG.md` file. Entries typically start with an asterisk and describe the change concisely.
```text
* Fix static asset mtime fallback.
```
--------------------------------
### VLQ Decoding Examples: Common Input Strings
Source: https://github.com/rails/sprockets/blob/main/guides/source_maps.md
Provides examples of VLQ decoding for various common input strings, demonstrating the expected array of decoded integer values.
```Ruby
vlq_decode("AAAA")
#=> [0, 0, 0, 0]
```
```Ruby
vlq_decode("GAAIA")
#=> [3, 0, 0, 4, 0]
```
--------------------------------
### Ruby: Install Dependencies and Run Tests for Sprockets
Source: https://github.com/rails/sprockets/blob/main/CONTRIBUTING.md
Execute `bundle install` to download and set up all necessary Ruby gem dependencies for the project. Run `bundle exec rake test` to ensure the entire test suite passes, verifying the project's integrity.
```ruby
bundle install
bundle exec rake test
```
--------------------------------
### Install Sprockets Ruby Gem
Source: https://github.com/rails/sprockets/blob/main/README.md
Instructions for installing the Sprockets library using RubyGems or by including it in a project's Gemfile with Bundler.
```Shell
gem install sprockets
```
```Ruby
gem 'sprockets', '~> 4.0'
```
--------------------------------
### Install Mozilla Source-Map npm Package
Source: https://github.com/rails/sprockets/blob/main/guides/source_maps.md
Command to install the source-map npm package, which is a library for consuming and generating source maps. This is used in the subsequent Node.js example to parse a source map.
```Shell
$ npm install source-map
```
--------------------------------
### Install Uglify-JS npm Package
Source: https://github.com/rails/sprockets/blob/main/guides/source_maps.md
Command to install the uglify-js npm package, which is used for JavaScript minification and source map generation. This is a prerequisite for the subsequent examples.
```Shell
$ npm install uglify-js
```
--------------------------------
### VLQ Decoding Example: 'gC' Detailed Walkthrough
Source: https://github.com/rails/sprockets/blob/main/guides/source_maps.md
Provides a detailed, step-by-step walkthrough of VLQ decoding for the string 'gC', showing the intermediate values of `digit`, `vlq`, and `shift` during each iteration, and the final decoded result.
```Ruby
vlq_decode("gC")
# => [16]
```
```Ruby
digit = BASE64_VALUES["g"]
# => 32
continuation = false if (digit & VLQ_CONTINUATION_BIT) == 0
# continuation does not change, still true
digit &= VLQ_BASE_MASK
# => 0
vlq += digit << shift
# => 0
shift += VLQ_BASE_SHIFT
# => 5
```
```Ruby
digit &= VLQ_BASE_MASK
# => 2
vlq += digit << shift
# => 64
```
```Ruby
vlq_decode("gC")
# => [32]
```
--------------------------------
### Example JavaScript Source Map File Structure
Source: https://github.com/rails/sprockets/blob/main/guides/source_maps.md
This snippet shows a basic JavaScript source map file (.map) for a single, unconcatenated JavaScript file. It illustrates the `version`, `sources`, `names`, and `mappings` fields, providing a concrete example of how source maps link generated code back to its original source.
```JSON
{
"version": 3,
"sources": ["foo.js"],
"names": [ ],
"mappings": "AAAA,GAAIA"
}
```
--------------------------------
### Example Source Map Mapping Object Structure
Source: https://github.com/rails/sprockets/blob/main/guides/source_maps.md
An example of a single mapping object extracted by the source-map library. It details the source file, generatedLine/generatedColumn in the minified code, and originalLine/originalColumn with the name in the original source.
```JSON
{
"source": 'foo.js',
"generatedLine": 1,
"generatedColumn": 3,
"originalLine": 1,
"originalColumn": 4,
"name": 'foo'
}
```
--------------------------------
### Sprockets JavaScript Require Directive Example
Source: https://github.com/rails/sprockets/blob/main/README.md
Demonstrates how to use the `require` directive within a JavaScript file to include external libraries, such as jQuery, ensuring they load before custom application code.
```JavaScript
//= require jquery
$().ready({
// my custom code here
})
```
--------------------------------
### Ruby CoffeeScript Processor Implementation Example
Source: https://github.com/rails/sprockets/blob/main/guides/how_sprockets_works.md
Provides the Ruby implementation of a CoffeScriptProcessor. It defines a call method that compiles CoffeeScript input data into JavaScript, handles source maps, and returns the processed data and map.
```Ruby
module CoffeScriptProcessor
def self.call(input)
data = input[:data]
js, map = input[:cache].fetch([self.cache_key, data]) do
result = CoffeScript.compile(data, sourceMap: true, sourceFiles: [input[:source_path]])
[result['js'], decode_source_maps(result['v3SourceMap'])]
end
map = SourceMapUtils.combine_source_maps(input[:metadata][:map]), map)
{ data: js, map: map }
end
}
```
--------------------------------
### Mount Sprockets Environment as Rack Application in Ruby
Source: https://github.com/rails/sprockets/blob/main/guides/building_an_asset_processing_framework.md
This Ruby config.ru example demonstrates how to mount a Sprockets::Environment instance as a Rack application. It sets up /assets as the mount point, configures asset load paths for JavaScript and stylesheets, and then runs the Sprockets environment. A separate map block handles the main Rack application.
```ruby
require 'sprockets'
map '/assets' do
environment = Sprockets::Environment.new
environment.append_path 'app/assets/javascripts'
environment.append_path 'app/assets/stylesheets'
run environment
end
map '/' do
run YourRackApp
end
```
--------------------------------
### Ruby Sprockets Processor Lambda Example
Source: https://github.com/rails/sprockets/blob/main/guides/how_sprockets_works.md
Demonstrates a minimal Sprockets processor implemented as a Ruby lambda. It takes an input hash, modifies the data (removes semicolons), and returns a new hash with the processed data.
```Ruby
-> (input) {
data = input[:data].gsub(';', '')
{ data: data }
}
```
--------------------------------
### Configure Gzip Compression for Sprockets Assets in Ruby
Source: https://github.com/rails/sprockets/blob/main/guides/building_an_asset_processing_framework.md
Demonstrates how to enable or disable Gzip compression for compiled assets in Sprockets. It also shows how to configure Sprockets to use the Zopfli algorithm for compression if the gem is installed.
```Ruby
env = Sprockets::Environment.new(".")
env.gzip = false
```
```Ruby
env = Sprockets::Environment.new(".")
env.gzip = :zopfli
```
--------------------------------
### CoffeeScript Variable Assignment
Source: https://github.com/rails/sprockets/blob/main/guides/source_maps.md
A simple CoffeeScript snippet demonstrating variable assignment, used as an example of original source code for source mapping.
```CoffeeScript
number = 42
```
--------------------------------
### Rails Sprockets 4 manifest.js for Specific Asset Linking
Source: https://github.com/rails/sprockets/blob/main/UPGRADING.md
This JavaScript snippet illustrates how to configure `manifest.js` in Sprockets 4 to link only specific application files as top-level targets, similar to Sprockets 3 behavior. It includes `application.css`, `application.js`, and an example `marketing.css`.
```JavaScript
//= link_tree ../images
//= link application.css
//= link application.js
//
// maybe another non-standard file?
//= link marketing.css
```
--------------------------------
### Rails Sprockets 3 Asset Precompilation Configuration
Source: https://github.com/rails/sprockets/blob/main/UPGRADING.md
This Ruby snippet demonstrates how to configure asset precompilation in Rails applications using Sprockets versions prior to 4. It adds 'marketing.css' to the list of assets to be precompiled, making it available for deployment.
```Ruby
config.assets.precompile += ["marketing.css"]
```
--------------------------------
### Sprockets Exporter Interface (Sprockets::Exporters::Base)
Source: https://github.com/rails/sprockets/blob/main/guides/extending_sprockets.md
This section details the expected interface for custom Sprockets exporters. It outlines the initialization parameters (asset, environment, directory), the setup method, the skip? method for conditional execution, and the call method for performing the actual write operation.
```APIDOC
Sprockets::Exporters::Base:
Initialization Parameters:
- asset: Instance of Sprockets::Asset
- environment: Instance of Sprockets::Environment
- directory: Instance of String
Methods:
- setup(): Called after initialization.
- skip?(logger: Sprockets::Logger):
Returns: boolean (true to skip exporter)
Description: Called synchronously. Use logger to indicate status.
- call():
Description: Performs asset writing. Potentially called in a new thread. Should not mutate global state.
Provided Helper: write(filename: String) yields IO object
```
--------------------------------
### Common Asset Helpers in sprockets-rails
Source: https://github.com/rails/sprockets/blob/main/guides/how_sprockets_works.md
These are examples of asset helper methods provided by the `sprockets-rails` gem. They are used in Rails views to generate HTML tags for including JavaScript and CSS assets, respectively, integrating Sprockets into the Rails asset pipeline.
```ruby
javascript_include_tag
stylesheet_link_tag
```
--------------------------------
### Sprockets Basic Require Directive
Source: https://github.com/rails/sprockets/blob/main/README.md
A fundamental example of the `require` directive, used to include another asset file. This directive is processed by Sprockets during asset compilation.
```JavaScript
//= require z.js
```
--------------------------------
### Register Sprockets Compressor
Source: https://github.com/rails/sprockets/blob/main/guides/how_sprockets_works.md
Shows the syntax for registering a compressor in Sprockets. This example registers the UglifierCompressor for application/javascript assets, associating it with the :uglify key.
```Ruby
register_compressor 'application/javascript', :uglify, UglifierCompressor
```
--------------------------------
### JavaScript Source Map Full Path Declaration
Source: https://github.com/rails/sprockets/blob/main/guides/source_maps.md
Example of a JavaScript source map comment specifying the full path to the source map file. This allows the browser to locate the map regardless of the current file's directory.
```JavaScript
//# sourceMappingURL=/assets/application.js.map
```
--------------------------------
### Register Sprockets Transformer
Source: https://github.com/rails/sprockets/blob/main/guides/how_sprockets_works.md
Illustrates the syntax for registering a transformer in Sprockets. This example registers CoffeScriptProcessor to convert text/coffeescript assets to application/javascript.
```Ruby
register_transformer 'text/coffescript', 'application/javascript', CoffeScriptProcessor
```
--------------------------------
### Sprockets Index File for Custom Load Order
Source: https://github.com/rails/sprockets/blob/main/README.md
Provides an example of a `foo/index.js` file, demonstrating how to explicitly require files within a folder using relative paths. This allows developers to define a specific load order, overriding the default alphabetical sorting.
```js
//= require ./foo.min.js
//= require ./foo-ui.js
```
--------------------------------
### Generated JavaScript from CoffeeScript Compilation
Source: https://github.com/rails/sprockets/blob/main/guides/source_maps.md
Shows an example of JavaScript code generated by the CoffeeScript compiler, illustrating how original CoffeeScript constructs are translated into JavaScript.
```JavaScript
// Generated by CoffeeScript 1.8.0
(function() {
var cubes, list, math, num, number, opposite, race, square,
__slice = [].slice;
number = 42;
# ...
```
--------------------------------
### Ruby Example of Checking VLQ Continuation Bit
Source: https://github.com/rails/sprockets/blob/main/guides/source_maps.md
This Ruby snippet illustrates how to check if the continuation bit is set in a Base64 digit using a bitwise AND operation. It shows that for 'A' (value 0), the continuation bit is not set, indicating the end of a VLQ segment.
```Ruby
digit = BASE64_VALUES["A"]
digit & VLQ_CONTINUATION_BIT
# => 0
```
--------------------------------
### Ruby: Registering New Mime Types in Sprockets
Source: https://github.com/rails/sprockets/blob/main/guides/extending_sprockets.md
These Ruby examples show how to register custom MIME types with Sprockets using `register_mime_type`. The first example registers `application/json` with `.json` extension and `unicode` charset. The second registers `application/ruby` for `.rb` files, demonstrating how to associate file extensions with their corresponding MIME types.
```ruby
Sprockets.register_mime_type 'application/json', extensions: ['.json'], charset: :unicode
Sprockets.register_mime_type 'application/ruby', extensions: ['.rb']
```
--------------------------------
### Register Sprockets Bundle Processor
Source: https://github.com/rails/sprockets/blob/main/guides/how_sprockets_works.md
Shows how to register a bundle processor in Sprockets for specific MIME types. This example registers the Bundle processor for JavaScript and CSS assets, indicating they should be concatenated.
```Ruby
register_bundle_processor 'application/javascript', Bundle
register_bundle_processor 'text/css', Bundle
```
--------------------------------
### Sprockets JavaScript Require Directive Example
Source: https://github.com/rails/sprockets/blob/main/guides/extending_sprockets.md
An example of a Sprockets directive used within a JavaScript file to include the contents of another asset, 'foo'. This directive is processed by the DirectiveProcessor.
```js
//= require "foo"
```
--------------------------------
### Example JavaScript Source Map Comment
Source: https://github.com/rails/sprockets/blob/main/guides/how_sprockets_works.md
This snippet shows a typical source map comment found at the end of a JavaScript file processed by Sprockets. This comment provides a URL to the corresponding source map file, allowing browsers to map compiled or minified code back to its original source for easier debugging.
```javascript
//# sourceMappingURL=application.js-bf4cd805a31db054ae1dr1417f5c8ce72s13468ae23cbdb19d4a3bb010eh11f3.map
```
--------------------------------
### Rails Sprockets 4 Linking Engine Manifest
Source: https://github.com/rails/sprockets/blob/main/UPGRADING.md
This JavaScript snippet demonstrates how to link an external Rails engine's asset manifest within your application's `manifest.js` file. It shows how the engine's own `manifest.js` can then use `link_directory` to expose its assets.
```JavaScript
// app/assets/config/manifest.js
//= link my_engine
// my_engine/app/assets/config/my_engine.js
//= link_directory ../stylesheets/my_engine .css
```
--------------------------------
### Registering HTML to JavaScript Transformer in Sprockets
Source: https://github.com/rails/sprockets/blob/main/guides/extending_sprockets.md
An example of registering a transformer to process HTML files and output them as JavaScript. This is useful for scenarios like template processors that convert HTML templates into executable JavaScript.
```ruby
Sprockets.register_transformer 'text/html', 'application/javascript', MyTemplateProcessor
```
--------------------------------
### Ruby VLQ Decode Example for Single Character
Source: https://github.com/rails/sprockets/blob/main/guides/source_maps.md
This Ruby snippet demonstrates the expected output of the `vlq_decode` function for a single 'A' character. It shows that a single 'A' (representing zero) results in an array containing a single zero.
```Ruby
str = "A"
vlq_decode(str)
# => [0]
```
--------------------------------
### JavaScript Source Map Relative Path Declaration
Source: https://github.com/rails/sprockets/blob/main/guides/source_maps.md
Example of a JavaScript source map comment specifying a relative path to the source map file. The browser resolves this path relative to the location of the JavaScript file.
```JavaScript
//# sourceMappingURL=application.js.map
```
--------------------------------
### Ruby VLQ Decode Example for Multiple Characters
Source: https://github.com/rails/sprockets/blob/main/guides/source_maps.md
This Ruby snippet demonstrates the expected output of the `vlq_decode` function for multiple 'A' characters. It shows that 'AAAA' (representing four zeros) results in an array containing four zeros, illustrating how multiple segments are decoded.
```Ruby
str = "AAAA"
vlq_decode(str)
# => [0, 0, 0, 0]
```
--------------------------------
### Ruby: Registering Directive Processor for Custom Comments
Source: https://github.com/rails/sprockets/blob/main/guides/extending_sprockets.md
This Ruby example demonstrates how to register a `DirectiveProcessor` with Sprockets for a specific MIME type, like `text/coffeescript`. It initializes the processor with a `comments` key, specifying the comment delimiters (e.g., `#` and `###`) that Sprockets should recognize when parsing directives within files of that type.
```ruby
Sprockets.register_preprocessor 'text/coffeescript', DirectiveProcessor.new(comments: ["#", ["###", "###"]])
```
--------------------------------
### Create Universal Sprockets Processor for Versions 2, 3, and 4
Source: https://github.com/rails/sprockets/blob/main/guides/extending_sprockets.md
This Ruby class demonstrates how to implement a Sprockets processor that is compatible with Sprockets versions 2, 3, and 4. It provides both a 'render' instance method for v2 compatibility and a 'self.call' class method for v3/v4 compatibility, allowing a single processor to work across multiple major versions. The example adds a simple comment to 'text/css' files.
```Ruby
# Sprockets 2, 3 & 4 interface
class MySprocketsExtension
def initialize(filename, &block)
@filename = filename
@source = block.call
end
def render(context, empty_hash_wtf)
self.class.run(@filename, @source, context)
end
def self.run(filename, source, context)
source + "/* Hello From my sprockets extension */"
end
def self.call(input)
filename = input[:filename]
source = input[:data]
context = input[:environment].context_class.new(input)
result = run(filename, source, context)
context.metadata.merge(data: result)
end
end
require 'sprockets/processing'
extend Sprockets::Processing
register_preprocessor 'text/css', MySprocketsExtension
```
--------------------------------
### Sprockets Gzip Asset File Naming Convention
Source: https://github.com/rails/sprockets/blob/main/README.md
Sprockets automatically generates gzipped copies of non-binary compiled assets. This example shows how a compiled CSS file `application-12345.css` will have a corresponding gzipped file `application-12345.css.gz`.
```text
application-12345.css
```
```text
application-12345.css.gz
```
--------------------------------
### Default Rails Sprockets 4 manifest.js Configuration
Source: https://github.com/rails/sprockets/blob/main/UPGRADING.md
This JavaScript snippet shows the default `manifest.js` file generated by `rails new` for Sprockets 4. It uses `link_tree` and `link_directory` directives to include assets from `images`, `javascripts`, and `stylesheets` directories as top-level targets.
```JavaScript
//= link_tree ../images
//= link_directory ../javascripts .js
//= link_directory ../stylesheets .css
```
--------------------------------
### Transpiled JavaScript Output from ES6 Asset
Source: https://github.com/rails/sprockets/blob/main/UPGRADING.md
The resulting JavaScript code after Sprockets 4 transpiles the ES6 asset using Babel. The arrow function from the ES6 input is converted into a standard function declaration.
```js
var square = function square(n) {
return n * n;
};
console.log(square);
```
--------------------------------
### Rails Sprockets 4 Asset Linking with asset_url Helper
Source: https://github.com/rails/sprockets/blob/main/UPGRADING.md
This CSS snippet, using ERB, shows how the `asset_url` helper automatically links assets within other assets. When `logo.png` is referenced, Sprockets recognizes it as a dependency and ensures it's compiled and publicly available.
```CSS
.logo {
background: url(<%= asset_url("logo.png") %>)
}
```
--------------------------------
### Example of Sprockets Generated JavaScript Script Tag
Source: https://github.com/rails/sprockets/blob/main/guides/how_sprockets_works.md
This snippet illustrates the HTML output generated by Sprockets for a JavaScript asset in development mode. It includes the asset's path, name, a debug suffix, a SHA1 digest of its content for cache busting, and the file extension. The 'debug' suffix indicates the use of Sprockets' debug pipeline.
```html
```
--------------------------------
### Add Babel Transpiler Gem to Gemfile
Source: https://github.com/rails/sprockets/blob/main/UPGRADING.md
To enable ES6 transpilation in Sprockets 4, include the 'babel-transpiler' gem in your application's Gemfile. This gem provides the necessary Babel processor for asset compilation.
```ruby
gem 'babel-transpiler'
```
--------------------------------
### Implement Sprockets 3.x+ Processor Interface
Source: https://github.com/rails/sprockets/blob/main/guides/extending_sprockets.md
This Ruby module demonstrates the modern Sprockets 3.x+ processor interface, which utilizes a 'self.call' class method. This interface is more flexible as the processor does not necessarily need to be a class, and it receives an 'input' hash containing relevant asset data. The example shows how to extract data and return a result.
```Ruby
# Sprockets 3.x+ interface
module MySprocketsExtension
def self.call(input)
# code
result = input[:data] # :data key holds source
{ data: result }
end
end
require 'sprockets/processing'
extend Sprockets::Processing
register_preprocessor 'text/css', MySprocketsExtension
```
--------------------------------
### Register Sprockets Engine in Sprockets 2 and 3 with Version Detection
Source: https://github.com/rails/sprockets/blob/main/guides/extending_sprockets.md
This example illustrates how to use `register_engine` to support both Sprockets 2 and 3 by dynamically adjusting arguments. Sprockets 2 does not accept a hash for options, so version detection is used to conditionally add the `mime_type` and `silence_deprecation` options only for Sprockets 3.
```Ruby
args = ['.css', MySprocketsExtension]
args << { mime_type: 'text/css', silence_deprecation: true } if Sprockets::VERSION.start_with?("3")
env.register_engine(*args)
```
--------------------------------
### Update sass-rails Gemfile Dependency for Sprockets 4
Source: https://github.com/rails/sprockets/blob/main/UPGRADING.md
Illustrates how to modify the 'sass-rails' gem dependency in a Rails 'Gemfile' to allow upgrading to Sprockets 4.x. It shows changing from a tilde operator (~>) to a greater-than-or-equal-to operator (>=) for compatibility, followed by the bundle update command to apply the changes.
```Ruby
gem 'sass-rails', '~> 5.0'
# or
gem 'sass-rails', '~> 5'
```
```Ruby
gem 'sass-rails', '>= 5'
```
```Shell
bundle update sass-rails sprockets
```
--------------------------------
### Initialize Sprockets Environment and Find Assets
Source: https://github.com/rails/sprockets/blob/main/guides/how_sprockets_works.md
This Ruby snippet demonstrates how to create a new Sprockets environment instance and then use it to locate a specific asset, such as 'application.js'. The environment is central to asset management in Sprockets.
```ruby
environment = Sprockets::Environment.new
environment.find_assets('application.js')
```
--------------------------------
### Precompile Assets using Sprockets Manifest in Ruby
Source: https://github.com/rails/sprockets/blob/main/guides/building_an_asset_processing_framework.md
This Ruby code illustrates a pattern for precompiling assets for production deployment using Sprockets::Manifest. It shows how to find and map logical paths of assets specified in config.assets.precompile into a set, preparing them for efficient serving.
```ruby
SprocketsManifest#find(config.assets.precompile).map(&:logical_path).to_set
```
--------------------------------
### Configure Rails Asset Precompilation List (Ruby)
Source: https://github.com/rails/sprockets/blob/main/guides/how_sprockets_works.md
This Ruby snippet shows how to explicitly add specific asset files, such as `application.js` and `application.css`, to the precompilation list in a Rails application's configuration. This ensures these assets are compiled and fingerprinted for production environments.
```ruby
Rails.application.config.assets.precompile << %w(application.js application.css)
```
--------------------------------
### VLQ Decoding Process: Intermediate Calculations
Source: https://github.com/rails/sprockets/blob/main/guides/source_maps.md
Illustrates the step-by-step calculations involved in Variable Length Quantity (VLQ) decoding, showing how `continuation`, `digit`, `vlq`, and `shift` variables are updated during the process, and the effect of the final right shift.
```Ruby
continuation = false if (digit & VLQ_CONTINUATION_BIT) == 0
# => false
digit &= VLQ_BASE_MASK
# => 1
vlq += digit << shift
# => 32
shift += VLQ_BASE_SHIFT
# => 10
```
```Ruby
vlq >> 1
# => [16]
```
--------------------------------
### Sprockets v3 Precompilation with Custom Proc (Ruby)
Source: https://github.com/rails/sprockets/blob/main/guides/how_sprockets_works.md
This Ruby code illustrates an older method from Sprockets version 3 for defining custom asset precompilation logic using a `Proc` (lambda). It identifies and includes all JavaScript and stylesheet files within the `app/assets` directory, excluding those with specific extensions, for precompilation.
```ruby
LOOSE_APP_ASSETS = lambda do |logical_path, filename|
filename.start_with?(::Rails.root.join('app/assets').to_s) &&
!['.js', '.css', ''].include?(File.extname(logical_path))
end
config.assets.precompile = [LOOSE_APP_ASSETS, /(?:/|\|A)application\.(.css|js)$/]
```
--------------------------------
### Configure Sprockets Environment Load Path in Ruby
Source: https://github.com/rails/sprockets/blob/main/guides/building_an_asset_processing_framework.md
This Ruby snippet demonstrates how to initialize a Sprockets::Environment and add directories to its asset load path. It uses append_path to include JavaScript assets from application, library, and vendor directories. Directories added later have lower precedence unless prepend_path is used for higher priority.
```ruby
environment = Sprockets::Environment.new
environment.append_path 'app/assets/javascripts'
environment.append_path 'lib/assets/javascripts'
environment.append_path 'vendor/assets/bower_components'
```
--------------------------------
### Create Sample JavaScript File for Uglify-JS
Source: https://github.com/rails/sprockets/blob/main/guides/source_maps.md
Content of a simple JavaScript file (foo.js) used as input for the uglify-js tool. This file will be minified and a source map will be generated from it.
```JavaScript
var foo = "foo";
var bar = "bar";
```
--------------------------------
### Access Sprockets Asset Programmatically in Ruby
Source: https://github.com/rails/sprockets/blob/main/guides/building_an_asset_processing_framework.md
Demonstrates how to retrieve a Sprockets::Asset instance using environment['logical_path']. It also explains how to access asset properties like content, length, modification time, and filename.
```Ruby
environment['application.js']
# => #
```
--------------------------------
### Listing Files in a JavaScript Directory
Source: https://github.com/rails/sprockets/blob/main/README.md
Shows the output of the `ls -1` command, listing files within the `my_javascript` directory. This illustrates the alphabetical order in which Sprockets would load these files when using `require_directory`.
```sh
$ ls -1 my_javascript/
alpha.js
beta.js
jquery.js
```
--------------------------------
### Generate PNG from SVG using Sprockets Link Directives (JavaScript)
Source: https://github.com/rails/sprockets/blob/main/guides/how_sprockets_works.md
Illustrates the use of `//= link` and `//= link_tree` directives in a JavaScript manifest file (e.g., `manifest.js`) to dynamically generate PNG versions from existing SVG files. This allows on-the-fly image conversion based on asset requests.
```javascript
// app/assets/config/manifest.js
// Given you have foo.svg
//= link foo.png
// or
//= link_tree ../images .png
```
--------------------------------
### Execute JavaScript in Ruby using ExecJS
Source: https://github.com/rails/sprockets/blob/main/guides/how_sprockets_works.md
This Ruby code demonstrates how to use the `execjs` gem to execute JavaScript code from within a Ruby environment. It requires the `execjs` library and then uses `ExecJS.eval` to run a JavaScript string, returning the result to Ruby.
```ruby
require 'execjs'
ExecJS.eval "'red yellow blue'.split(' ')"
```
--------------------------------
### Sprockets Simple Path Require
Source: https://github.com/rails/sprockets/blob/main/README.md
Illustrates requiring a file by its name, relying on Sprockets to search its configured load paths for the asset. This simplifies directives when assets are discoverable via load paths.
```JavaScript
//= require foo.js
```
--------------------------------
### Correct Asset Path for Sprockets Index Files
Source: https://github.com/rails/sprockets/blob/main/README.md
Shows the correct way to reference an index file. Instead of `foo/index.js`, the asset should be requested as `foo.js`, as the index file acts as a proxy for the folder.
```erb
<%= asset_path("foo.js") %>
```
--------------------------------
### Precompile Rails Assets for Production
Source: https://github.com/rails/sprockets/blob/main/README.md
This command demonstrates how to precompile assets for a Rails application in a production environment. Running `rake assets:precompile` generates static asset files ready for serving by a web server like Nginx or Rails' public file server.
```term
$ RAILS_ENV=production rake assets:precompile
```
--------------------------------
### Register a Transformer in Sprockets Environment
Source: https://github.com/rails/sprockets/blob/main/guides/how_sprockets_works.md
This Ruby code shows how to register a custom transformer, `SVGTransformer`, within the Sprockets environment. Transformers are used to process assets, converting them from one MIME type to another, for example, SVG to another image format.
```ruby
environment = Sprockets::Environment.new
Environment.register_transformer 'image/svg+xml', 'image/svg', SVGTransformer.new
```
--------------------------------
### Sprockets Single Processor File Extension
Source: https://github.com/rails/sprockets/blob/main/README.md
Demonstrates a basic SCSS file named `application.scss`, which Sprockets automatically processes using the SASS processor, converting it to CSS.
```text
application.scss
```
--------------------------------
### Sprockets v4 `link` Directives for Asset Manifests (JavaScript)
Source: https://github.com/rails/sprockets/blob/main/guides/how_sprockets_works.md
This JavaScript snippet showcases the new `link` directives introduced in Sprockets version 4, used within `manifest.js` files. Directives like `link_tree`, `link_directory`, and `link` provide a clearer and more modular way to specify assets for inclusion and precompilation, including those from engines.
```js
// app/assets/config/manifest.js
//= link_tree ../images
//= link_directory ../javascripts .js
//= link_directory ../stylesheets .css
//= link my_engine
// my_engine/app/assets/config/my_engine.js
//= link_tree ../images/bootstrap
```
--------------------------------
### Configure JavaScript and CSS Minifiers in Rails
Source: https://github.com/rails/sprockets/blob/main/README.md
This snippet shows how to configure JavaScript and CSS compressors in a Rails application's `config/application.rb` or an environment-specific file. It uses `:terser` for JavaScript and `:scss` for CSS.
```ruby
config.assets.js_compressor = :terser
config.assets.css_compressor = :scss
```
--------------------------------
### Implement SVG to PNG Conversion Logic (Ruby)
Source: https://github.com/rails/sprockets/blob/main/guides/how_sprockets_works.md
Defines the `SvgTransformer` class, which contains the core logic for converting SVG source data to PNG using the RMagick library. The `call` method processes the SVG input and returns the generated PNG as a binary blob, fulfilling the transformation registered by Sprockets.
```ruby
require 'rmagick'
class SvgTransformer
def self.call(input)
image_list = Magick::Image.from_blob(input[:data]) { self.format = 'SVG' }
image = image_list.first
image.format = 'PNG'
{ data: image.to_blob }
end
end
```
--------------------------------
### Requiring a Folder via its Index File
Source: https://github.com/rails/sprockets/blob/main/README.md
Shows how an `application.js` file can require an entire folder's contents by referencing its index file (e.g., `foo.js` for `foo/index.js`). This allows for controlled ordering within the index file.
```js
//= require foo.js
```
--------------------------------
### Client-side JavaScript Templating with EJS and JST
Source: https://github.com/rails/sprockets/blob/main/README.md
Demonstrates a client-side EJS template (`.jst.ejs`) and its usage in JavaScript. Templates are compiled to functions accessible via the global `JST` object, allowing dynamic rendering of HTML.
```EJS
Hello, <%= name %>!
```
```JavaScript
// application.js
//= require templates/hello
$("#hello").html(JST["templates/hello"]({ name: "Sam" }));
```
--------------------------------
### Registering a Sprockets Postprocessor
Source: https://github.com/rails/sprockets/blob/main/guides/extending_sprockets.md
Similar to preprocessor registration, this snippet demonstrates how to register a custom processor as a postprocessor. It applies the `HelloWorldProcessor` to JavaScript files after other processing, allowing for final modifications.
```Ruby
Sprockets.register_postprocessor('application/javascript', HelloWorldProcessor.new)
```
--------------------------------
### Rails Asset Path Helper for Compiled Assets
Source: https://github.com/rails/sprockets/blob/main/README.md
Shows how to use the `asset_path` helper in Rails to request a compiled asset. Sprockets understands that `application.scss.erb` will compile to `application.css`, allowing developers to request the final output extension.
```erb
asset_path("application.css")
```
--------------------------------
### Sprockets Relative Path Require
Source: https://github.com/rails/sprockets/blob/main/README.md
Demonstrates using a relative path with the `require` directive to include a file located in a parent directory. This allows for flexible file organization within your asset structure.
```JavaScript
//= require ../foo.js
```
--------------------------------
### Configure JavaScript and CSS Minifiers for Sprockets Environment
Source: https://github.com/rails/sprockets/blob/main/README.md
For applications not using Rails, this snippet demonstrates how to directly set JavaScript and CSS compressors on the Sprockets `environment` object. Ensure `terser` and `sass` gems are included in your Gemfile if using a Rack app.
```ruby
environment.js_compressor = :terser
environment.css_compressor = :scss
```
--------------------------------
### Registering a Sprockets Preprocessor
Source: https://github.com/rails/sprockets/blob/main/guides/extending_sprockets.md
This snippet shows how to register a custom processor as a preprocessor for a specific MIME type. It associates the `HelloWorldProcessor` instance with JavaScript files, ensuring it runs before other processing steps.
```Ruby
Sprockets.register_preprocessor('application/javascript', HelloWorldProcessor.new)
```
--------------------------------
### Sprockets `require_directory` Directive
Source: https://github.com/rails/sprockets/blob/main/README.md
The `require_directory` directive includes all source files of the same format within a specified directory. Files are included in alphabetical order, providing a way to bundle entire folders of assets efficiently.
```APIDOC
`require_directory` *path* requires all source files of the same format in the directory specified by *path*. Files are required in alphabetical order.
```
```JavaScript
//= require_directory alphabet
```
```JavaScript
var a = "A";
var b = "B";
```
--------------------------------
### Sprockets `require` Directives for Asset Bundling (JavaScript)
Source: https://github.com/rails/sprockets/blob/main/guides/how_sprockets_works.md
This JavaScript code snippet demonstrates the use of `require` and `require_tree` directives within `application.js`. These special comments instruct Sprockets to include specified JavaScript files and all files within a directory, respectively, when bundling assets for a Rails application.
```js
// app/assets/javascripts/application.js
//= require jquery
//= require jquery-ui
//= require users
//= require_tree .
```
--------------------------------
### Sprockets Require Directory Directive
Source: https://github.com/rails/sprockets/blob/main/README.md
Demonstrates the `//= require_directory` directive in JavaScript, which includes all files from a specified directory. Files are loaded in alphabetical order by default, which can cause issues with dependency ordering.
```js
//= require_directory my_javascript
```
--------------------------------
### Sprockets Require Tree Directive
Source: https://github.com/rails/sprockets/blob/main/README.md
Demonstrates the `//= require_tree .` directive, which includes all files and subdirectories from the current directory. Similar to `require_directory`, it loads files alphabetically, potentially causing dependency issues.
```js
//= require_tree .
```
--------------------------------
### Sprockets Processor `call` Method Input Hash Keys
Source: https://github.com/rails/sprockets/blob/main/guides/extending_sprockets.md
This section documents the various keys available in the input hash passed to a Sprockets processor's `call` method. It describes the purpose and expected type of each key, such as `:data`, `:uri`, `:filename`, and `:metadata`, providing context for processor development.
```APIDOC
Processor Input Hash Keys:
- :data: [String] Contains the contents of the file.
Example: 'var foo = "bar"'
- :uri: [String] A full URI to the asset, may include custom Sprockets params.
Example: "file:///Users/richardschneeman/Documents/projects/sprockets/test/fixtures/default/application.coffee?type=application/javascript"
- :filename: [String] Full path to asset on disk.
Example: "/Users/richardschneeman/Documents/projects/sprockets/test/fixtures/default/gallery.js\""
- :load_path: [String] The load path that was used to find the asset.
Example: "/Users/richardschneeman/Documents/projects/sprockets/test/fixtures/default"
- :name: [String] The name of the file being loaded without extension.
Example: "gallery"
- :content_type: [String] The corresponding mime content type of the asset.
Example: "application/javascript"
- :metadata: [Hash] Extra data.
Example: { dependencies: [].to_set, map: { # ... } }
- :cache: [Sprockets::Cache] A cache object for storing/retrieving intermediate objects.
Methods: Cache#get, Cache#set, Cache#fetch.
Note: Use Sprockets::Environment#compress_from_root and #expand_from_root for paths.
- :environment: [Sprockets::Environment] Direct access to Sprockets environment methods.
Note: Use carefully, subject to change.
```
--------------------------------
### Compile CoffeeScript to JavaScript using ExecJS in Ruby
Source: https://github.com/rails/sprockets/blob/main/guides/how_sprockets_works.md
This snippet demonstrates how to use the 'execjs' gem in Ruby to compile CoffeeScript code. It fetches the CoffeeScript compiler from a URL, compiles it using 'ExecJS.compile', and then calls the 'CoffeeScript.compile' function to transform a CoffeeScript expression into JavaScript.
```ruby
require 'execjs'
require 'open-uri'
source = open('https://coffeescript.org/v1/browser-compiler/coffee-script.js').read
context = ExecJS.compile(source)
context.call('CoffeeScript.compile', 'square = (x) -> x * x', bare: true)
# => "var square;\nsquare = function(x) {\n return x * x;\n};"
```
--------------------------------
### Sprockets Asset Directives Reference
Source: https://github.com/rails/sprockets/blob/main/README.md
A comprehensive list of available Sprockets directives used to control asset concatenation, dependency management, and compilation behavior within asset files.
```APIDOC
- require: Add the contents of a file to current
- require_self: Change order of where current contents are concatenated to current
- require_directory: Add contents of each file in a folder to current
- require_tree: Add contents of all files in all directories in a path to current
- link: Make target file compile and be publicly available without adding contents to current
- link_directory: Make target directory compile and be publicly available without adding contents to current
- link_tree: Make target tree compile and be publicly available without adding contents to current
- depend_on: Recompile current file if target has changed
- depend_on_directory: Recompile current file if any files in target directory has changed
- stub: Ignore target file
```
--------------------------------
### Transpile ES6 JavaScript to ES5 with Sprockets
Source: https://github.com/rails/sprockets/blob/main/README.md
Illustrates an ES6 JavaScript asset (`.es6` extension) and its corresponding transpiled ES5 output. Sprockets automatically processes `.es6` files using Babel, making modern JavaScript compatible with older environments.
```ES6
// app/assets/javascript/application.es6
var square = (n) => n * n
console.log(square);
```
```JavaScript
var square = function square(n) {
return n * n;
};
console.log(square);
```
--------------------------------
### Generate Minified JavaScript and Source Map using Uglify-JS
Source: https://github.com/rails/sprockets/blob/main/guides/source_maps.md
Command to run uglifyjs on foo.js to produce a minified version and a corresponding source map file (foo.js.map). The --source-map flag is crucial for map generation.
```Shell
$ uglifyjs foo.js --source-map foo.js.map
```
--------------------------------
### Load NPM Module via Sprockets Directive (JavaScript)
Source: https://github.com/rails/sprockets/blob/main/guides/how_sprockets_works.md
Demonstrates how to use the `//= npm` directive within a JavaScript asset file (e.g., `my_component.js`) to load an NPM module like `lodash`. This directive relies on the previously registered `NpmDirectiveProcessor` to resolve the module.
```javascript
// app/assets/javascripts/my_component.js
//= npm lodash
```
--------------------------------
### Sprockets Processor Input Hash Structure
Source: https://github.com/rails/sprockets/blob/main/guides/how_sprockets_works.md
Defines the default keys available in the input hash passed to a Sprockets processor. It includes keys for asset data, environment, cache, URI, paths, name, content type, and metadata.
```APIDOC
Input Hash Keys:
- :data (String): The string contents of the asset
- :environment (Sprockets::Environment): The current Sprockets::Environment instance
- :cache (Sprockets::Cache): The Sprockets::Cache instance
- :uri (String): The asset URI
- :source_path (String): The full path to original file
- :load_path (String): The current load path for the file
- :name (String): The logical name of the file
- :content_type (String): The MIME type of the output asset
- :metadata (Hash): The Hash of processor metadata
```
--------------------------------
### Enable Sprockets JavaScript Compressor
Source: https://github.com/rails/sprockets/blob/main/guides/how_sprockets_works.md
Demonstrates how to enable a registered JavaScript compressor on a Sprockets environment instance. This sets the js_compressor to :uglify, activating the previously registered Uglifier compressor.
```Ruby
env.js_compressor = :uglify
```
--------------------------------
### Ruby: Registering Multi-Part File Extensions for Mime Types
Source: https://github.com/rails/sprockets/blob/main/guides/extending_sprockets.md
This Ruby snippet illustrates how to register a MIME type for multi-part file extensions, such as `.js.coffee`. By registering the full extension, Sprockets processes the file as a single unit (e.g., `text/coffeescript`) rather than attempting to chain multiple processors, ensuring correct handling of complex file types.
```ruby
Sprockets.register_mime_type 'text/coffeescript', extensions: ['.coffee', '.js.coffee']
```
--------------------------------
### Sprockets Manifest Fingerprinted to Detailed Asset Mapping
Source: https://github.com/rails/sprockets/blob/main/guides/how_sprockets_works.md
This Ruby hash illustrates a more detailed entry in the Sprockets manifest. It provides a reverse mapping from the fingerprinted filename back to its logical path, along with metadata like modification time (`mtime`) and the digest value.
```ruby
{
"application-2e8e9a7888bdbd11e97effec30214a82.js" =>
{
"logical-path" => "application.js",
"mtime" => "2016-06-16T23:09:08-06:00",
"digest" => "2e8e9a7888bdbd11e97effec30214a82"
}
}
```
--------------------------------
### Define Asset Dependencies with Sprockets Directives across Languages
Source: https://github.com/rails/sprockets/blob/main/guides/building_an_asset_processing_framework.md
Illustrates the syntax for Sprockets directive comments in various languages (CSS, JavaScript, CoffeeScript). These comments are used to specify asset dependencies and are processed by Sprockets to build asset bundles.
```CSS
/* Multi-line comment blocks (CSS, SCSS, JavaScript)
*= require foo
*/
```
```JavaScript
// Single-line comment blocks (SCSS, JavaScript)
//= require foo
```
```CoffeeScript
# Single-line comment blocks (CoffeeScript)
#= require foo
```
--------------------------------
### Sprockets `require_self` Directive
Source: https://github.com/rails/sprockets/blob/main/README.md
The `require_self` directive instructs Sprockets to insert the body of the current source file at the beginning of the compiled output, before any subsequent `require` directives. This allows for prepending file-specific code within a concatenated bundle.
```APIDOC
`require_self` tells Sprockets to insert the body of the current source file before any subsequent `require` directives.
```
```JavaScript
var a = "A";
```
```JavaScript
//= require_self
//= require 'a.js'
var app_name = "Sprockets";
```
```JavaScript
var app_name = "Sprockets";
var a = "A";
```
--------------------------------
### Sprockets Explicit Require for Dependency Order
Source: https://github.com/rails/sprockets/blob/main/README.md
Provides an alternative to `require_directory` by explicitly listing files with `//= require`. This method ensures that files are loaded in the specified order, resolving potential dependency issues.
```js
//= require jquery
//= require alpha
//= require beta
```
--------------------------------
### Git: Configure Global User Name and Email for Commits
Source: https://github.com/rails/sprockets/blob/main/CONTRIBUTING.md
Set your global Git user name and email address. These credentials will be associated with all your future commits, ensuring proper attribution in the commit history.
```shell
git config --global user.name "Your Name"
git config --global user.email "contributor@example.com"
```
--------------------------------
### Sprockets Directive Comment Syntax
Source: https://github.com/rails/sprockets/blob/main/README.md
Illustrates the various comment block formats that Sprockets recognizes for directives across different asset file types, including multi-line and single-line comments.
```CSS
/* Multi-line comment blocks (CSS, SCSS, JavaScript)
*= require foo
*/
```
```JavaScript
// Single-line comment blocks (SCSS, JavaScript)
//= require foo
```
```CoffeeScript
# Single-line comment blocks (CoffeeScript)
#= require foo
```