Skip to content

Instantly share code, notes, and snippets.

@lethe2211
Last active August 29, 2015 14:04
Show Gist options
  • Save lethe2211/66a865f4de1b98f47c98 to your computer and use it in GitHub Desktop.
Save lethe2211/66a865f4de1b98f47c98 to your computer and use it in GitHub Desktop.
# -*- coding: utf-8 -*-
require 'json'
require 'fileutils'
=begin
JSONファイルを用いたファイルキャッシュ
=end
class JsonCache
def initialize(dir: "cache/")
@abspath = File.dirname(__FILE__)
@dir = dir
@prefix = "cache_"
@postfix = ".json"
FileUtils.mkdir_p("#{ @abspath }/#{ @dir }") unless File.exist?("#{ @abspath }/# { @dir }") # ディレクトリがなければ作る
end
# 保存したキャッシュファイルをオブジェクトの形で取り出す
def get(key, defValue: nil)
relpath = "/#{ @dir }#{ @prefix }#{ key.to_s }#{ @postfix }"
if not File.exists?(@abspath + relpath)
return defValue
end
f = open(@abspath + relpath, "r")
json = f.read
result = JSON.parse(json)
f.close
return result
end
# RubyオブジェクトをJSONに変換し,ファイルに保存する
def set(key, value)
relpath = "/#{ @dir }#{ @prefix }#{ key.to_s }#{ @postfix }"
open(@abspath + relpath, "w") do |io|
JSON.dump(value, io)
end
end
end
if __FILE__ == $0
j = JsonCache.new
j.set("lethe2211", {id: "lethe2211", favorite: ["programming", "anime"]} # cache/に"cache_lethe2211.json"が作成され,データが格納される
p j.get("lethe2211") # => {"id"=>"lethe2211", "favorite"=>["programming", "anime"]}
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment