Sprockets::StaticAsset

`StaticAsset`s are used for files that are served verbatim without any processing or concatenation. These are typical images and other binary files.

Public Class Methods

new(environment, logical_path, pathname, digest = nil) click to toggle source
# File lib/sprockets/static_asset.rb, line 15
def initialize(environment, logical_path, pathname, digest = nil)
  super(environment, logical_path, pathname)
  @digest = digest
  load!
end
serialized_attributes() click to toggle source

Define extra attributes to be serialized.

# File lib/sprockets/static_asset.rb, line 11
def self.serialized_attributes
  super + %( content_type mtime length digest )
end

Public Instance Methods

body() click to toggle source

Returns file contents as its `body`.

# File lib/sprockets/static_asset.rb, line 22
def body
  # File is read everytime to avoid memory bloat of large binary files
  pathname.open('rb') { |f| f.read }
end
fresh?() click to toggle source

Checks if Asset is fresh by comparing the actual mtime and digest to the inmemory model.

# File lib/sprockets/static_asset.rb, line 29
def fresh?
  # Check current mtime and digest
  dependency_fresh?('path' => pathname, 'mtime' => mtime, 'hexdigest' => digest)
end
to_path() click to toggle source

Implemented for Rack SendFile support.

# File lib/sprockets/static_asset.rb, line 35
def to_path
  pathname.to_s
end
to_s() click to toggle source

`to_s` is aliased to body since static assets can’t have any dependencies.

# File lib/sprockets/static_asset.rb, line 40
def to_s
  body
end
write_to(filename, options = {}) click to toggle source

Save asset to disk.

# File lib/sprockets/static_asset.rb, line 45
def write_to(filename, options = {})
  # Gzip contents if filename has '.gz'
  options[:compress] ||= File.extname(filename) == '.gz'

  if options[:compress]
    # Open file and run it through `Zlib`
    pathname.open('rb') do |rd|
      File.open("#{filename}+", 'wb') do |wr|
        gz = Zlib::GzipWriter.new(wr, Zlib::BEST_COMPRESSION)
        buf = ""
        while rd.read(16384, buf)
          gz.write(buf)
        end
        gz.close
      end
    end
  else
    # If no compression needs to be done, we can just copy it into place.
    FileUtils.cp(pathname, "#{filename}+")
  end

  # Atomic write
  FileUtils.mv("#{filename}+", filename)

  # Set mtime correctly
  File.utime(mtime, mtime, filename)

  nil
ensure
  # Ensure tmp file gets cleaned up
  FileUtils.rm("#{filename}+") if File.exist?("#{filename}+")
end

[Validate]

Generated with the Darkfish Rdoc Generator 2.