一旦我添加额外的方法调用,Sinatra就不会发送响应

时间:2011-03-30 22:52:00

标签: ruby sinatra

post '/payment/transactions/amount' do # => creates a new charge
content_type :json, :charset => 'utf-8'

class Transaction
def initialize(endUserId, code, referenceCode, callback=false)
  @endUserId = endUserId
  @code = code
  @referenceCode = referenceCode 
  $callback = callback
  $transId = rand(1000)                               
end 

def transId
  return $transId 
end

def callback
  return $callback
end 

def postCallback
  sleep(5)
  RestClient.post"#{$callback}", :message => 'CALLBACK SUCCESS', :content_type => :json
end  

def to_json(*a)     
  {"amountTransaction" => {
    "endUserId" => @endUserId,
    "paymentAmount" =>{
      "chargingInformation" => {"code" => @code, "description" => @description},
         "totalAmountCharged"=> "0" 
     },
     "referenceCode" => @referenceCode,
     "serverReferenceCode" =>"#{(0...6).map{65.+(rand(25)).chr}.join}", # just an example, can be any string
     "resourceURL" => "http://localhost:4567/payment/#{@endUserId}/transactions/amount/#{Trans.transId}",
     "transactionOperationStatus" => "Processing"
 }}.to_json(*a)
end
end 

 Trans = Transaction.new(params[:endUserId],params[:code], params[:referenceCode],    params[:callback])
 jsonTrans = Trans.to_json
 receipts.addReceipt(Trans.transId,jsonTrans)
 jsonTrans 
 # fire callback
 if Trans.callback then 
  sleep(10)
  Trans.postCallback 
 end  
end 

对我来说问题是#fire回调之后的代码。如果我省略了这个...然后,jsonTrans JSON对象按预期返回。当我包含if ...然后触发回调,然后在5秒后发生所需的Trans.postcallback - 但是不返回前面的jsonTrans,它只是被忽略。关于我做错了什么的任何想法?要确认,所需的行为是在HTTP响应中返回jsonTrans,然后在5秒后调用postCallback方法(假设if计算结果为true)。干杯!

通过生成新主题

编辑解决了:     Thread.new {       如果Trans.callback那么        休眠状态(5)       Trans.postCallback      结束}     jsonTrans

2 个答案:

答案 0 :(得分:1)

最后一个语句是该方法返回(输出)的内容,因此它会忽略输出中的jsonTrans。

我的第一个想法就是重新排序:

 #... 
 Trans = Transaction.new(params[:endUserId],params[:code], params[:referenceCode],    params[:callback])
 jsonTrans = Trans.to_json
 receipts.addReceipt(Trans.transId,jsonTrans) 
 # fire callback
 if Trans.callback then 
  sleep(10)
  Trans.postCallback 
 end  
 jsonTrans
end 

如果你不期望RestClient.post - 呼叫的任何输出,这应该有用。

答案 1 :(得分:0)

感谢daddz的建议 - 实际上我设法通过生成一个新线程来解决它:Thread.new{ if Trans.callback then sleep(5) Trans.postCallback end} jsonTrans