Created
February 2, 2011 19:17
-
-
Save cowboy/808205 to your computer and use it in GitHub Desktop.
A very simple wrapper around Ruby's Marshal (tested in ruby 1.9.2p136)
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
# Ruby MarshalCache - v0.1 - 02/2/2011 | |
# http://benalman.com/ | |
# | |
# Copyright (c) 2011 "Cowboy" Ben Alman | |
# Dual licensed under the MIT and GPL licenses. | |
# http://benalman.com/about/license/ | |
require 'zlib' | |
# A very basic cache that uses Marshal internally. | |
# Inspired by Marcus Westin's http://bit.ly/g3BLyp | |
class MarshalCache | |
def initialize(root, gzip = false) | |
@root = root | |
@gzip = gzip | |
end | |
# If file at path exists, return its value, otherwise create it with the | |
# value returned by the specified block. | |
def get(path) | |
path = File.join(@root, path) | |
obj = nil | |
if File.exist?(path) | |
block = lambda {|file| obj = Marshal.load(file)} | |
if @gzip | |
Zlib::GzipReader.open(path, &block) | |
else | |
File.open(path, 'rb', &block) | |
end | |
elsif block_given? | |
obj = yield | |
block = lambda {|file| Marshal.dump(obj, file)} | |
if @gzip | |
Zlib::GzipWriter.open(path, &block) | |
else | |
File.open(path, 'wb', &block) | |
end | |
end | |
obj | |
end | |
end |
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
$cache = MarshalCache.new('/tmp') | |
text = $cache.get('cache_test') do | |
p 'GENERATING TEXT' | |
'This is a line of text!' | |
end | |
p text |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment