praggerのキャッシュプラグインを書いてみた
CGI化したのはいいけど、何度も起動してRSS::loadしまくったらサーバに迷惑かけるかもしれない、ということでキャッシュプラグインを書いてみました。
ソースは以下の通り。(バグってないかな?)
## cache data plugin -- nak2k ## ## - module: cache ## config: ## fresh: 1h ## filename: cache.yaml ## module: RSS::load ## config: ## url: http://hogehoge ## ## or ## ## - module: cache ## config: ## fresh: 1h ## filename: cache.yaml ## modules: ## - module: foo ## - module: bar ## - module: baz ## def cache(config, data) filename = config["filename"] || "cache.yaml" if File.file?(filename) t = config["fresh"] || "1h" t = t.to_i * (60) if t=~/m$/ t = t.to_i * (60*60) if t=~/h$/ t = t.to_i * (60*60*24) if t=~/d$/ if Time.now < File.stat(filename).mtime + t return YAML.load(File.read(filename)) end end data = eval_pragger(config["modules"] || [config], []) open(filename, "w") { |w| w.puts YAML.dump_stream(data) } return data end
追記
Filter::fresh を参考に時間指定部分を修正。