Monday, November 12, 2007

Mongrelhandler + erb

A few weeks back I wrote a MongrelHandler to handle concurrent requests on a site to
process a slow running process(read scraping) in background. Here is how it looks like (in essence)


class < Mongrel::HttpHandler
def get_binding
binding
end
def process(request, response)
response.start(200) do |head, out|
head["Content-Type"] = "text/html"
params={}
request.params["QUERY_STRING"].split('&').each{|x|
k,v=x.split('=')
params[k.to_sym]=v
}
params[:id]=request.params["PATH_INFO"]
@posts=Post.find(params[:id]) #or whatever
template=""
File.open("#{RAILS_ROOT}/app/views/<path>/<filename>", "r"){
|f| template=f.readlines.to_s
}
rhtml = ERB.new(template)
str=rhtml.result(self.get_binding)
out.write str
end
end
end


To start it call
mongrel_rails start -e environment -p port -S path-to-mongrel-handler