Created
December 11, 2010 02:36
-
-
Save rummelonp/737101 to your computer and use it in GitHub Desktop.
ActiveSupport::Cache::FileStoreを使ったリクエストラッパーのサンプル
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
require 'rubygems' | |
require 'active_support/core_ext/numeric/time' | |
require 'active_support/cache' | |
require 'addressable/template' | |
require 'net/http' | |
require 'xmlsimple' | |
module MyTumblr | |
extend self | |
ApiRead = Addressable::Template.new 'http://{user}.tumblr.com/api/read' | |
def api_read(user, params = {}) | |
url = ApiRead.expand :user => user | |
parse_response url, params | |
end | |
private | |
def parse_response(url, params) | |
url.query_values = params | |
body = get_url url | |
XmlSimple.xml_in body | |
end | |
def get_url(url) | |
response = Net::HTTP.start(url.host, url.port) do |http| | |
http.get url.request_uri | |
end | |
if Net::HTTPSuccess === response | |
response.body | |
else | |
response.error! | |
end | |
end | |
module Cache | |
extend MyTumblr | |
class << self | |
attr_accessor :cache | |
def setup(cache_dir, options = {}) | |
options.update({ | |
:namespace => 'my_tumblr' | |
}) | |
self.cache = ActiveSupport::Cache::FileStore.new(cache_dir, options) | |
end | |
private | |
def get_url(url) | |
cache.fetch(url.to_s) { super } | |
end | |
end | |
end | |
end | |
if __FILE__ == $0 | |
# リクエストを投げる | |
data = MyTumblr::api_read('mitukiii') | |
# キャッシュを5分有効にする | |
MyTumblr::Cache::setup(ENV['TMPDIR'], {:expires_in => 5.minutes}) | |
# キャッシュされたデータがあればそれを返し | |
# なければリクエストを投げる | |
MyTumblr::Cache::api_read('mitukiii') | |
MyTumblr::Cache::api_read('mitukiii') | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment