Garbage
class Apa
def initialize = ( @lu = {} )
def method_missing(k, v = nil) = ( v ?
(@lu[k] = v) : @lu.key?(k) ? @lu[k] : nil )
def _sto(file) = ( File.write(file, Marshal.dump(@lu), mode: 'wb') )
def _rec(file) = ( @lu = Marshal.load(File.read(file)) )
def _eval(k) = ( @lu[k] = eval(@lu[k]) )
end
I was hoping to be able to serialize a full set of data, procs, lambdas. But it still has’nt worked out that way. What I got so far is a stupid workaround where procs and lambdas must be stored as strings and then evaluated.
=begin
If Apa can not find the method, it is caught by
'method_missing'. The name of the method is sent as
parameter.
If method_missing gets a SECOND parameter (default = nil)
the function assumes you are using a SET_METHOD.
(@lu[key] = value)
If method_missing only receives ONE parameter, it assumes
you are using a GET_METHOD.
(return @lu[k])
If @lu do not have that key, nil is returned.
serialization:
_sto(filename) Saves the hash (lu) to file.
_rec(filename) Sets the hash (lu) to the content of the file.
NB! Not possible to serialize lambdas and procs..
a workaround is to keep them as string and then modify them with eval.
_eval(key) Sets hash value of (lu) to the eval(itself)
=end
x = Apa.new
# store and retrieve a string
x.name 'Kakan'
p x.name # => Kakan
# store and retrieve (use) a lambda
x.add ->(a,b) {a+b}
p x.add.(3,4) # => 7
# store and retrieve an array
x.numbers [*1..5]
p x.numbers # => [1, 2, 3, 4, 5]
# store array and proc and filter array with proc
x.fifteen [*1..15]
x.even proc {|x| x.even? }
enum = x.fifteen.select(&x.even)
enum.each {p _1}
# => 2 4 6 8 10 12 14
# use getting for setting
x.kalas x.numbers.map(&:to_s).join
p x.kalas # "12345"
# testing marshaling
skit = Apa.new
skit.apekatt 'Hej baberiba!'
skit.nummer 33
skit._sto('fisoxe.class')
pnisse = Apa.new
pnisse._rec('fisoxe.class')
p pnisse.nummer
p pnisse.apekatt
pnisse.test 'proc {|x| x*2}'
p pnisse.test.class # String
pnisse._eval :test
p pnisse.test.class # Proc
p pnisse.test[8] # 16