module MIME::Types::Cache

Public Instance Methods

load(cache_file = nil) click to toggle source

Attempts to load the cache from the file provided as a parameter or in the environment variable RUBY_MIME_TYPES_CACHE. Returns nil if the file does not exist, if the file cannot be loaded, or if the data in the cache version is different than this version.

# File lib/mime/types/cache.rb, line 17
def load(cache_file = nil)
  cache_file = cache_file || ENV['RUBY_MIME_TYPES_CACHE']
  return nil unless cache_file and File.exist?(cache_file)

  cache = Marshal.load(File.binread(cache_file))
  if cache.version == MIME::Types::VERSION
    Marshal.load(cache.data)
  else
    warn "Could not load MIME::Types cache: invalid version"
    nil
  end
rescue => e
  warn "Could not load MIME::Types cache: #{e}"
  return nil
end
save(types = nil, cache_file = nil) click to toggle source

Attempts to save the types provided to the cache file provided.

If types is not provided or is nil, the cache will contain the current MIME::Types default registry.

If cache_file is not provided or is nil, the cache will be written to the file specified in the environment variable RUBY_MIME_TYPES_CACHE. If there is no cache file specified either directly or through the environment, this method will return nil

# File lib/mime/types/cache.rb, line 42
def save(types = nil, cache_file = nil)
  cache_file = cache_file || ENV['RUBY_MIME_TYPES_CACHE']
  return nil unless cache_file

  types      = types || MIME::Types.send(:__types__)

  File.open(cache_file, 'wb') do |f|
    f.write(Marshal.dump(new(types.data_version, Marshal.dump(types))))
  end
end