制作回滚类 - Ruby

时间:2017-10-22 20:55:39

标签: ruby transactions rollback

我需要创建一个充当回滚器的类。

class Rollbacker
def perform(*args, &block)
  begin
    objCopy, @originalState = args

    objCopy.each do |i|
      i.instance_eval(&block)
    end
  rescue
    objCopy = @originalState //Here i tried also with args = originalState
    raise
  end
end

我遇到的问题是“执行”工作正常(块使用args执行正常),但是当救援发生时(并且错误被提出),我需要args返回它的原始状态而没有更改“开始”,但没有发生。

如果我没有弄错,在“开始”我正在制作一份args副本,然后在救援中更改它,但不知道为什么不工作

有关改变什么的想法?

1 个答案:

答案 0 :(得分:-1)

一个例子是,有一个类Klass:

class Klass
attr_accessor :counter

def initialize(c)
  @counter= c
end

def plus
  self.counter = self.counter+ 1
end
end
---------------------------  

rollbacker.perform(Klass.new(0)) {|k| k.plus} //this leaves the counter in 1. Currently working fine

---------------------------
k = Klass.new(0)
def kaboom(k)
  tr.perform(k) {|k|
    k.plus
    raise 'Kaboom!'}
end                    //This should raise the error (which it does), but the counter should stay on 0; but at the moment it stays in 1 (the plus happens, but not rollback is happening)