LogAn/lib/logan/cache.rb

80 lines
1.3 KiB
Ruby
Raw Normal View History

2010-03-28 14:33:49 +02:00
2010-03-29 18:50:04 +02:00
class LogAn::Cache
2010-03-28 14:33:49 +02:00
READ = 1
WRITE = 2
attr_reader :source, :data
def initialize source, type = nil, data = nil
type ||= READ | WRITE
@source, @data, self.type = source, data || {}, type
end
def flush!
@data.each {|k,v| @obj[k] = v }
@data = {}
end
def dget k
@data[k] ||= @obj[k]
end
def oget k
@data[k] || @obj[k]
end
def dset k, v
@data[k] ||= v
end
def oset k, v
@obj[k] = v
end
def type= type
2010-03-29 19:20:52 +02:00
self.read_cache, self.write_cache = type & 1 > 0, type & 2 > 0
2010-03-28 14:33:49 +02:00
type
end
def read_cache= type
@type &= ~ (type ? 0 : 1)
2010-03-29 19:22:43 +02:00
define_singleton_method :[], method( type ? :oget : :dget)
2010-03-28 14:33:49 +02:00
end
def write_cache= type
@type &= ~ (type ? 0 : 2)
2010-03-29 19:22:43 +02:00
define_singleton_method :[], method( type ? :oset : :dset)
2010-03-28 14:33:49 +02:00
end
#include Enumerable
#def each &e
#return Enumerator.new self, :each unless e
#flush!
#@obj.each &e
#self
#end
end
2010-03-29 18:50:04 +02:00
class LogAn::AutoValueConvertHash
2010-03-28 14:33:49 +02:00
include Enumerable
def initialize obj, encode = nil, each = nil, &decode
@object, @encoder = obj, decode.nil? ? encode || Marshal.method( :dump) : nil,
@each = each || obj.method( :each) rescue NameError
@decode = decode || Marshal.method( :restore)
end
def [] k
decode.call @object[k]
end
def []= k, v
@object[k] = encode.call v
end
def each *paras
@each.call *paras do |k, v|
yield k, decode( v)
end
end
end