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.
-
.set(key, value) ⇒ StringIO
Cache file content and metadata.
Class Attribute Details
.cache_path ⇒ Object
Returns the value of attribute cache_path.
28 29 30 |
# File 'lib/open-uri/cached.rb', line 28 def cache_path @cache_path end |
Class Method Details
.get(key) ⇒ StringIO
Retrieve file content and meta data from cache
34 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 |
# File 'lib/open-uri/cached.rb', line 34 def get(key) filename = filename_from_url(key) # TODO: head request to determine last_modified vs file modtime # Read metadata, if it exists = YAML::load(File.read("#{filename}.meta")) if File.exists?("#{filename}.meta") f = File.exists?(filename) ? StringIO.new(File.open(filename, "rb") { |f| f.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
107 108 109 110 111 112 |
# File 'lib/open-uri/cached.rb', line 107 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 |
.set(key, value) ⇒ StringIO
Cache file content and metadata
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 |
# File 'lib/open-uri/cached.rb', line 80 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 |