Kevsy
Kevsy

Reputation: 605

Sinatra not sending response once I add an extra method call

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 

Problem for me is the code following #fire callback. If I omit this if...then , the jsonTrans JSON object is returned as expected. When I include the if...then to fire the callback, then the desired Trans.postcallback occurs after 5 seconds - but the preceding jsonTrans is not returned, it is simply ignored. Any ideas on what I'm doing wrong? To confirm, the desired behaviour is to return the jsonTrans in the HTTP response and then call the postCallback method after 5 seconds (assuming the if evaluates to true). Cheers!

EDIT: Solved by spawning a new thread: Thread.new{ if Trans.callback then sleep(5) Trans.postCallback end} jsonTrans

Upvotes: 1

Views: 483

Answers (2)

Kevsy
Kevsy

Reputation: 605

Thanks for the suggestion daddz - actually I managed to solve it by wrapping by spawning a new thread: Thread.new{ if Trans.callback then sleep(5) Trans.postCallback end} jsonTrans

Upvotes: 0

scable
scable

Reputation: 4084

The last statement is what the method returns(outputs) so it ignores your jsonTrans in the output.

The first idea I have would be to reorder it:

 #... 
 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 

This should work if you don't expect any output from that RestClient.post-call.

Upvotes: 1

Related Questions