0

When streaming as shown in Ruby on Rails 3: Streaming data through Rails to client I'm running into an issue where the after_filter and around_filter are finished executing prior to the response. I need the response to be streamed prior to the after_filters being executed since we are relying on data that gets cleaned up in those filters. I am using passenger.

Example controller:

class Asdf
  def each
    (1..5).each do |num|
      sleep(1)
      Rails.logger.info "STREAMING LINE #{num}"
      yield "test#{num}\n"
    end
  end
end

class WelcomeController < ApplicationController
  before_filter :before
  after_filter :after

  around_filter do |controller, action|
    logger.debug "around_filter prior to action"
    action.call
    logger.debug "around_filter after action"
  end

  def index
    self.response.headers['Last-Modified'] = Time.now.to_s

    self.response_body = Asdf.new                                                  
  end

  def before
    Rails.logger.info "before_filter called"
  end

  def after
    Rails.logger.info "after_filter called"
  end

end

Example log output (timing reflects that it is streaming)

Started GET "/welcome/index" for 192.168.74.64 at 2016-01-25 17:28:17 -0600
Processing by WelcomeController#index as HTML
before_filter called
around_filter prior to action
around_filter after action
after_filter called
Completed 200 OK in 0.7ms (ActiveRecord: 0.0ms)
STREAMING LINE 1
STREAMING LINE 2
STREAMING LINE 3
STREAMING LINE 4
STREAMING LINE 5
Community
  • 1
  • 1
Cody Gustafson
  • 1,440
  • 11
  • 13

1 Answers1

1

It seems like, rather than relying on around_filter, you might be able to invoke your data clean-up routine in the class's each method after the iterator has been exhausted:

class Asdf
  def each
    (1..5).each do |num|
      sleep(1)
      Rails.logger.info "STREAMING LINE #{num}"
      yield "test#{num}\n"
    end
    Rails.logger.info "ALL DONE; READY TO CLEAN UP"
    clean_up
  end

  def clean_up
    Rails.logger.info "CLEANING UP"
  end
end

Hititng the welcome#index action in a Rails 3.2 app yielded the following in the log:

Started GET "/welcome" for 127.0.0.1 at 2016-01-25 18:55:49 -0800
Processing by WelcomeController#index as HTML
before_filter called
around_filter prior to action
around_filter after action
after_filter called
Completed 200 OK in 0.5ms (ActiveRecord: 0.0ms)
STREAMING LINE 1
STREAMING LINE 2
STREAMING LINE 3
STREAMING LINE 4
STREAMING LINE 5
ALL DONE; READY TO CLEAN UP
CLEANING UP
konacaret
  • 181
  • 5
  • Thanks @konacaret. I wanted to avoid that because my other non-streaming methods are currently using filters within railties. – Cody Gustafson Jan 26 '16 at 04:22