2016-01-25 26 views
0

当按照Ruby on Rails 3: Streaming data through Rails to client中所示进行流式传输时,我遇到了after_filter和around_filter在响应之前完成执行的问题。我需要在执行after_filters之前对响应进行流式传输,因为我们依赖的是在这些过滤器中清理的数据。我正在使用乘客。轨道流控制中的意外过滤器行为

例控制器:

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 

实例日志输出(正反映了它是流)

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 

回答

1

好像,而不是依赖于around_filter,你也许能够调用您的数据在迭代器耗尽后,该类的each方法中的清理例程:

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在Rails 3.2的应用程序的welcome#index动作产生的日志中的以下内容:@konacaret

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 
+0

感谢。我想避免这种情况,因为我的其他非流式方法目前正在使用railties内的过滤器。 –