Skip to content

Added two new middleware classes (UserAgent & Cache)#6

Open
glenux wants to merge 5 commits intosukria:masterfrom
glenux:master
Open

Added two new middleware classes (UserAgent & Cache)#6
glenux wants to merge 5 commits intosukria:masterfrom
glenux:master

Conversation

@glenux
Copy link

@glenux glenux commented Aug 11, 2011

UserAgent

I think UserAgent is quite explicit, but here is an use case :

require 'spore/middleware/useragent'

foobar = Spore.new("foobar.json")
foobar.enable(Spore::Middleware::UserAgent, 
    :useragent => 'Mozilla/5.0 (X11; Linux x86_64; rv:2.0b4) Gecko/20100818 Firefox/4.0b4')
foobar.api_call(...)

Cache

A very simple example:

require 'spore/middleware/cache'

foobar = Spore.new("foobar.json")
foobar.enable(Spore::Middleware::Cache, :storage => {} )
foobar.api_call(...)

A more complex example, using files for cache

require 'spore/middleware/cache'
require 'base64'
require 'fileutils'

class DirectoryCache
    include Enumerable

    def initialize directory
        @root = File.expand_path directory

        FileUtils.mkdir_p @root if not File.exist? @root
    end

    def include? key
        path = _key_to_path key
        return (File.exist? path)
    end

    def []= key, value
        path = _key_to_path key
        File.open path, "w" do |fh|
            fh.puts value   
        end
    end

    def each &blk
        d = Dir.new @root
        d.each do |x|
            next if x == '.' or x == '..'
            yield x
        end
    end

    private

    def _key_to_path key
        path =  File.join @root, Base64.encode64(key)
        return path
    end

end

cache = DirectoryCache.new "cache.d"

foobar = Spore.new("foobar.json")
foobar.enable(Spore::Middleware::Cache, :storage => cache )
foobar.api_call(...)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant