Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a method after a view has been rendered in rails 3

I have a task which will take around 20 - 30 seconds. I want this task to run immediately after a view is rendered. I want the output of this task to be stored in a session variable. What is the simplest way to do it rails 3.

To explain what i need exactly. I am showing a list of tweets to users (this is the view rendered) They have to go through them. I want a method to be invoked after this view is rendered which will take the same tweets and cluster them (20-30 seconds process). I should have the results of the clustering in the session so that i can display them in the next page.

How do I do this?

like image 805
shishirmk Avatar asked Nov 23 '25 14:11

shishirmk


2 Answers

You should be able to do it in the controller method that renders the view. Just add the code after 'render' call. For example:

  def index
    @tweets = Tweet.all

    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @tweets }
    end
    # do something with tweets
    puts "#{@tweets}"
  end
like image 187
Salil Avatar answered Nov 25 '25 03:11

Salil


This is how I solved the problem

  1. I used resque for background tasks. I enqueued the task just before the render was called.
  2. I coded the background worker to put the result of the clustering in a redis cache.
  3. The controller where the clusters are supposed to be shown, I read the results from redis, deserialized them and rendered them.

It was not perfect but it was fast enough for a research feedback collection tool.

like image 42
shishirmk Avatar answered Nov 25 '25 03:11

shishirmk