Class: OpenURI::Cache
- Inherits:
-
Object
- Object
- OpenURI::Cache
- Defined in:
- lib/open-uri/cached.rb
Class Attribute Summary collapse
-
.cache_path ⇒ Object
Returns the value of attribute cache_path.
Class Method Summary collapse
-
.get(key) ⇒ StringIO
Retrieve file content and meta data from cache.
-
.invalidate(key, time = Time.now) ⇒ Object
Invalidate cache for a key, optionally if older than time givan.
-
.invalidate_all! ⇒ Object
Invalidate all caches we know about.
-
.set(key, value) ⇒ StringIO
Cache file content and metadata.
Class Attribute Details
.cache_path ⇒ Object
Returns the value of attribute cache_path.
29 30 31 |
# File 'lib/open-uri/cached.rb', line 29 def cache_path @cache_path end |
Class Method Details
.get(key) ⇒ StringIO
Retrieve file content and meta data from cache
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 |
# File 'lib/open-uri/cached.rb', line 35 def get(key) filename = filename_from_url(key) # TODO: head request to determine last_modified vs file modtime # Read metadata, if it exists if File.exist?("#{filename}.meta") if YAML.respond_to?(:unsafe_load) = YAML.unsafe_load(File.read("#{filename}.meta")) else = YAML.load(File.read("#{filename}.meta")) end end f = File.exist?(filename) ? StringIO.new(File.open(filename, "rb") { |fd| fd.read }) : nil # Add meta accessors if && f f.instance_variable_set(:"@meta", ) def f. @meta end def f.base_uri @meta[:base_uri] end def f.content_type @meta[:content_type] end def f.charset @meta[:charset] end def f.content_encoding @meta[:content_encoding] end def f.last_modified @meta[:last_modified] end def f.status @meta[:status] end end f end |
.invalidate(key, time = Time.now) ⇒ Object
Invalidate cache for a key, optionally if older than time givan
114 115 116 117 118 119 |
# File 'lib/open-uri/cached.rb', line 114 def invalidate(key, time = Time.now) filename = filename_from_url(key) File.delete(filename) if File.stat(filename).mtime < time rescue Errno::ENOENT false end |
.invalidate_all! ⇒ Object
Invalidate all caches we know about
122 123 124 |
# File 'lib/open-uri/cached.rb', line 122 def invalidate_all! FileUtils.rm_r(@cache_path, force: true, secure: true) end |
.set(key, value) ⇒ StringIO
Cache file content and metadata
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 |
# File 'lib/open-uri/cached.rb', line 87 def set(key, value) filename = filename_from_url(key) mkpath(filename) # Save metadata in a parallel file if value.respond_to?(:meta) = "#{filename}.meta" = value. [:status] = value.status if value.respond_to?(:status) [:content_type] = value.content_type if value.respond_to?(:content_type) [:base_uri] = value.base_uri if value.respond_to?(:base_uri) File.open(, 'wb') {|f| YAML::dump(, f)} end # Save file contents File.open(filename, 'wb'){|f| f.write value.read } value.rewind value end |