如何使用 rails 上的转换 gem 处理事件机器中的错误?

How to handle error in event machine using transitions gem on rails?

我在 rails 4.2 中的事件机(转换 gem)上工作,我写了一个名为 send_data 的方法,当状态从挂起变为交付时,send_data 将被解雇。

def send_data
    data = { 'remote_id' => order.remote_id,
             'items' => order.line_items
           }
    SendLineItemsToWebshop.call(data)        
  end

SendLineItemsToWebshop 是另一个 class 调用 call 方法并等待一些响应,如果响应到来,那么事件将被触发(状态将被改变),否则,状态将相同。

require 'bunny'
require 'thread'
class SendLineItemsToWebshop
  def self.call(data)
    conn = Bunny.new(automatically_recover: false)
    conn.start
    channel = conn.create_channel
    response = call_client(channel, data)
    channel.queue(ENV['BLISS_RPC_QUEUE_NAME']).pop
    channel.close
    conn.close
    self.response(response)
  end

  def self.call_client(channel, data)
    client = RpcClient.new(channel, ENV['BLISS_RPC_QUEUE_NAME'])
    client.call(data)
  end

  def self.response(response)
    return response
    JSON.parse response
  end
end

但问题是当调用事件 deliver 时,它不会检查 send_data 的响应是否到来,它会更改状态。这是我的送货活动:

event :deliver do
      transitions :to => :delivered, :from => [:editing, :pending] , on_transition: [ :send_data ]
    end

但我希望如果response为false或nil,过渡状态不会改变。只有当响应为真时,状态才会改变。 请帮我解决这个问题。

Transitions gem 有一个不错的 guard 功能。添加一个简单的逻辑测试,如 can_be_delivered? 然后试试这个:

event :deliver do
  transitions :to => :delivered, :from => [:editing, :pending], guard: [:can_be_delivered?]
end