Class: Sprockets::StaticAsset

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

Overview

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

Instance Attribute Summary

Attributes inherited from Asset

#content_type, #digest, #length, #logical_path, #mtime, #pathname

Instance Method Summary collapse

Methods inherited from Asset

#body, #dependencies, #digest_path, #each, #encode_with, #eql?, #fresh?, from_hash, #hash, #init_with, #initialize, #inspect, #stale?, #to_a, #to_s

Constructor Details

This class inherits a constructor from Sprockets::Asset

Instance Method Details

#sourceObject

Returns file contents as its ‘source`.



11
12
13
14
# File 'lib/sprockets/static_asset.rb', line 11

def source
  # File is read everytime to avoid memory bloat of large binary files
  pathname.open('rb') { |f| f.read }
end

#to_pathObject

Implemented for Rack SendFile support.



17
18
19
# File 'lib/sprockets/static_asset.rb', line 17

def to_path
  pathname.to_s
end

#write_to(filename, options = {}) ⇒ Object

Save asset to disk.



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
53
54
55
56
# File 'lib/sprockets/static_asset.rb', line 22

def write_to(filename, options = {})
  # Gzip contents if filename has '.gz'
  options[:compress] ||= File.extname(filename) == '.gz'

  FileUtils.mkdir_p File.dirname(filename)

  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)
        gz.mtime = mtime.to_i
        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