root/lang/ruby/open-uri-cache/trunk/lib/open-uri/cache.rb @ 4640

Revision 4640, 2.0 kB (checked in by walf443, 5 years ago)

lang/ruby/open-uri-cache: add memcache cache engine.

Line 
1require 'stringio'
2require 'open-uri'
3require 'singleton'
4
5module OpenURI
6  # interface for auto caching open-uri
7  #
8  class Cache
9    include Singleton
10
11    class << self
12      alias instance_original instance
13
14      def instance
15        unless @engine
16        end
17       
18        instance_original
19      end
20
21      def method_missing meth, *args, &block
22        instance.__send__(meth, *args, &block)
23      end
24
25    end
26
27    attr_reader :engine
28    attr_accessor :enabled
29
30    def engine= val
31      @engine = val.instance
32    end
33
34    def enable!
35      @enabled = true
36      # hook point for engine class
37      if @engine.methods.include? :enable!
38        @engine.enable!
39      end
40    end
41
42    def enabled?
43      @enabled
44    end
45
46    def disabled?
47      !@enabled
48    end
49
50    def disable!
51      @enabled = false
52      # hook point for engine class
53      if @engine.methods.include? :diable!
54        @engine.disable!
55      end
56    end
57
58    # if it isn't defined method in this class, call engine class method.
59    def method_missing meth, *args, &block
60      @engine.__send__(meth, *args, &block)
61    end
62
63    # if you write orignal engine, please include this module for checking.
64    module Lint
65      def self.instance
66        raise NotImplementedError
67      end
68
69      def set key, val
70        raise NotImplementedError
71      end
72
73      def get key
74        raise NotImplementedError
75      end
76    end
77
78    # you should raise this error or subclass in engine class.
79    class Error < ::Exception; end
80  end
81 
82  # override OpenURI.open with Cache.
83  class << self
84    alias open_without_cache open
85
86    def open(uri, *rest, &block)
87      if Cache.enabled
88        begin
89          res = Cache.get(uri.to_s)
90        rescue
91          res = nil
92        end
93      else
94        return open_without_cache(uri, *rest, &block)
95      end
96
97      unless res
98        res = open_without_cache(uri, *rest, &block).read
99        Cache.set(uri.to_s, res)
100      end
101
102      return StringIO.new(res)
103    end
104  end
105end
Note: See TracBrowser for help on using the browser.