LogAn/lib/logan/cache.rb

82 lines
1.4 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!
2010-03-29 23:12:43 +02:00
@data.each {|k,v| @source[k] = v }
2010-03-28 14:33:49 +02:00
@data = {}
end
def dget k
2010-03-29 23:12:43 +02:00
@data[k] ||= @source[k]
2010-03-28 14:33:49 +02:00
end
def oget k
2010-03-29 23:12:43 +02:00
@data[k] || @source[k]
2010-03-28 14:33:49 +02:00
end
def dset k, v
@data[k] ||= v
end
def oset k, v
2010-03-29 23:12:43 +02:00
@source[k] = v
2010-03-28 14:33:49 +02:00
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 22:36:57 +02:00
define_singleton_method :[]=, method( type ? :oset : :dset)
2010-03-28 14:33:49 +02:00
end
2010-03-30 01:22:48 +02:00
include Enumerable
def each
return Enumerator.new self, :each unless e
(@source.keys + @data.keys).each do |key|
yield key, self[key]
end
self
end
2010-03-28 14:33:49 +02:00
end
2010-03-29 18:50:04 +02:00
class LogAn::AutoValueConvertHash
2010-03-28 14:33:49 +02:00
include Enumerable
2010-03-29 22:36:57 +02:00
attr_reader :decode, :encode
2010-03-28 14:33:49 +02:00
2010-03-29 23:12:43 +02:00
def initialize source, encode = nil, each = nil, &decode
@source, @encoder = source, decode.nil? ? encode || Marshal.method( :dump) : nil,
@each = each || source.method( :each) rescue NameError
2010-03-28 14:33:49 +02:00
@decode = decode || Marshal.method( :restore)
end
def [] k
2010-03-29 23:12:43 +02:00
@decode.call @source[k]
2010-03-28 14:33:49 +02:00
end
def []= k, v
2010-03-29 23:12:43 +02:00
@source[k] = @encode.call v
2010-03-28 14:33:49 +02:00
end
def each *paras
@each.call *paras do |k, v|
2010-03-29 22:36:57 +02:00
yield k, @decode.call( v)
2010-03-28 14:33:49 +02:00
end
end
end