在跨库事务操作时,我们会用上这样的代码
A::User.transaction do
B::User.transaction do
C::User.transaction do
D::User.transaction do
end
end
end
end
有 A,B,C,D 四个库需要同时做事务操作(真实环境确实有这么多库)
为了完成以上的代码我这样做了一个简化
module Support
module Consistency
def self.transaction(*args, &block)
invalid_consts = args.select { |const| !const.respond_to?(:transaction)}
if invalid_consts.present?
raise "#{invalid_consts.map(&:to_s).join(',')}, they arent the sub class for ActiveRecord::Base".colorize(:red)
end
# TODO: I think there are better codes
cmd = ''
args.each do |const|
cmd << "#{const}.transaction {"
end
cmd << 'yield block'
args.each do |_|
cmd << '}'
end
eval cmd
end
end
end
Support::Consistency.transaction(A::User, B::User, C::User, D::User).transaction do
....
end
请问有更优雅的办法重构这块代码么?