LogAn/lib/logan/cache.rb

93 lines
1.7 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
2010-03-30 11:43:59 +02:00
def each *paras
2010-03-30 01:23:37 +02:00
return Enumerator.new self, :each unless block_given?
2010-03-30 11:43:59 +02:00
flush! if @type&2 == 2
@source.each_keys( *paras) do |key|
2010-03-30 01:22:48 +02:00
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
attr_reader :source
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, @encode = source, decode.nil? ? encode || Marshal.method( :dump) : encode,
@each, @decode = each, decode || Marshal.method( :restore)
@each ||= source.method( :each) rescue NameError
define_method :encode, &@encode if @encode
define_method :decode, &@decode if @decode
2010-03-28 14:33:49 +02:00
end
def [] k
decode @source[k]
2010-03-28 14:33:49 +02:00
end
def []= k, v
@source[k] = encode v
2010-03-28 14:33:49 +02:00
end
def each *paras
2010-03-30 11:43:59 +02:00
return Enumerator.new self, :each unless block_given?
2010-03-28 14:33:49 +02:00
@each.call *paras do |k, v|
yield k, decode( v)
2010-03-28 14:33:49 +02:00
end
end
2010-03-30 11:43:59 +02:00
def each_keys *paras
return Enumerator.new self, :each_keys unless block_given?
@each.call *paras do |k, v|
yield k
end
end
2010-03-28 14:33:49 +02:00
end