Class: MIME::Types::Cache
- Inherits:
-
Struct
- Object
- Struct
- MIME::Types::Cache
- Defined in:
- lib/mime/types/cache.rb,
lib/mime/types/cache.rb
Overview
Caching of MIME::Types registries is advisable if you will be loading the default registry relatively frequently. With the class methods on MIME::Types::Cache, any MIME::Types registry can be marshaled quickly and easily.
The cache is invalidated on a per-version basis; a cache file for version 2.0 will not be reused with version 2.0.1.
Instance Attribute Summary collapse
-
#data ⇒ Object
Returns the value of attribute data.
-
#version ⇒ Object
Returns the value of attribute version.
Class Method Summary collapse
-
.load(cache_file = nil) ⇒ Object
Attempts to load the cache from the file provided as a parameter or in the environment variable
RUBY_MIME_TYPES_CACHE
. -
.save(types = nil, cache_file = nil) ⇒ Object
Attempts to save the types provided to the cache file provided.
Instance Attribute Details
#data ⇒ Object
Returns the value of attribute data
4 5 6 |
# File 'lib/mime/types/cache.rb', line 4 def data @data end |
#version ⇒ Object
Returns the value of attribute version
4 5 6 |
# File 'lib/mime/types/cache.rb', line 4 def version @version end |
Class Method Details
.load(cache_file = nil) ⇒ Object
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.
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
# File 'lib/mime/types/cache.rb', line 19 def load(cache_file = nil) 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 MIME::Types.logger.warn <<-warning.chomp Could not load MIME::Types cache: invalid version warning nil end rescue => e MIME::Types.logger.warn <<-warning.chomp Could not load MIME::Types cache: #{e} warning return nil end |
.save(types = nil, cache_file = nil) ⇒ Object
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
48 49 50 51 52 53 54 55 56 57 |
# File 'lib/mime/types/cache.rb', line 48 def save(types = nil, cache_file = nil) cache_file ||= ENV['RUBY_MIME_TYPES_CACHE'] return nil unless cache_file 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 |