thesecretmaster thesecretmaster - 6 months ago 10
Ruby Question

Can I redirect before processing input?

What I currently have is this:

get "/" do
submitMeToTheDatabase = veryLongFunction(params[:processme])
Information.create(complicatedInformation:submitMeToTheDatabase)
redirect "/otherPage"
end


Would it work the same way, but have improved load times for the user if I did this?

get "/" do
redirect "/otherPage"
submitMeToTheDatabase = veryLongFunction(params[:processme])
Information.create(complicatedInformation:submitMeToTheDatabase)
end


Addendum

What would be another way to accomplish the same thing? Something along the lines of:

get "/" do
fork do
submitMeToTheDatabase = veryLongFunction(params[:processme])
Information.create(complicatedInformation:submitMeToTheDatabase)
end
redirect "/otherPage"
end

Answer

It's been a while since I've used sinatra, but I don't think the second would work.

The source for the redirect method shows that redirect calls halt (source) and immediately stops any further processing.

You could put the task onto a job queue and process it on another thread. See here to get an idea of what I mean.

queue = Queue.new
get "/" do
    queue << params[:processme]
    redirect "/otherPage"
end

consumer = Thread.new do
    loop do
        data = queue.pop
        submitMe = veryLongFunction(data)
        Information.create(complicatedInformation:submitMeToTheDatabase)
    end
end

Code not tested.