module Sprockets::Mime
def read_file(filename, content_type = nil)
Returns String file contents transcoded to UTF-8 or in its external
content_type - String MIME type
filename - String path
Public: Read file on disk with MIME type specific encoding.
def read_file(filename, content_type = nil) data = File.open(filename, 'rb') { |f| f.read } if type = mime_types[content_type] if charset = type[:charset] data = charset.call(data).encode(Encoding::UTF_8) end end data end
def read_input(input)
def read_input(input) read_file(input[:filename], input[:content_type]) end
def register_encoding(name, encode)
encode - Method/Proc to encode data
key - String name
register_encoding :gzip, EncodingUtils::GZIP
Examples
Public: Register a new encoding.
def register_encoding(name, encode) mutate_config(:encodings) do |encodings| encodings.merge(name.to_s => encode) end end
def register_mime_type(mime_type, options = {})
See EncodingUtils.
charset: Proc/Method that detects the charset of a file.
extensions: Array of String extnames
options - Hash
mime_type - String MIME Type
Public: Register a new mime type.
def register_mime_type(mime_type, options = {}) # Legacy extension argument, will be removed from 4.x if options.is_a?(String) options = { extensions: [options] } end extnames = Array(options[:extensions]).map { |extname| Sprockets::Utils.normalize_extension(extname) } charset = options[:charset] charset ||= EncodingUtils::DETECT if mime_type.start_with?('text/') mutate_config(:mime_exts) do |mime_exts| extnames.each do |extname| mime_exts[extname] = mime_type end mime_exts end mutate_config(:mime_types) do |mime_types| type = { extensions: extnames } type[:charset] = charset if charset mime_types.merge(mime_type => type) end end
def unwrap_encoding_processors(encoding)
encoding - String encoding.
Internal: Get a postprocessor to perform the encoding.
def unwrap_encoding_processors(encoding) processors = [] if encoder = self.encodings[encoding] processors << lambda do |input| { data: encoder.call(input[:data]), encoding: encoding } end end processors end