Skip to content
This repository
Browse code

raise exceptions on header set after response committed

  • Loading branch information...
commit 06c9e176ca1b74e99bc258295bfbd8d2f2f33563 1 parent 01b8126
Aaron Patterson authored July 29, 2012
21  actionpack/lib/action_controller/metal/live.rb
... ...
@@ -1,4 +1,5 @@
1 1
 require 'action_dispatch/http/response'
  2
+require 'delegate'
2 3
 
3 4
 module ActionController
4 5
   module Live
@@ -30,6 +31,26 @@ def close
30 31
         end
31 32
       end
32 33
 
  34
+      class Header < DelegateClass(Hash)
  35
+        def initialize(response, header)
  36
+          @response = response
  37
+          super(header)
  38
+        end
  39
+
  40
+        def []=(k,v)
  41
+          if @response.committed?
  42
+            raise ActionDispatch::IllegalStateError, 'header already sent'
  43
+          end
  44
+
  45
+          super
  46
+        end
  47
+      end
  48
+
  49
+      def initialize(status = 200, header = {}, body = [])
  50
+        header = Header.new self, header
  51
+        super(status, header, body)
  52
+      end
  53
+
33 54
       private
34 55
 
35 56
       def build_buffer(response, body)
3  actionpack/lib/action_dispatch.rb
@@ -36,6 +36,9 @@ module Rack
36 36
 module ActionDispatch
37 37
   extend ActiveSupport::Autoload
38 38
 
  39
+  class IllegalStateError < StandardError
  40
+  end
  41
+
39 42
   autoload_under 'http' do
40 43
     autoload :Request
41 44
     autoload :Response
19  actionpack/test/dispatch/live_response_test.rb
@@ -40,6 +40,25 @@ def test_content_length_is_removed
40 40
         @response.stream.write 'omg'
41 41
         assert_nil @response.headers['Content-Length']
42 42
       end
  43
+
  44
+      def test_headers_cannot_be_written_after_write
  45
+        @response.stream.write 'omg'
  46
+
  47
+        e = assert_raises(ActionDispatch::IllegalStateError) do
  48
+          @response.headers['Content-Length'] = "zomg"
  49
+        end
  50
+
  51
+        assert_equal 'header already sent', e.message
  52
+      end
  53
+
  54
+      def test_headers_cannot_be_written_after_close
  55
+        @response.stream.close
  56
+
  57
+        e = assert_raises(ActionDispatch::IllegalStateError) do
  58
+          @response.headers['Content-Length'] = "zomg"
  59
+        end
  60
+        assert_equal 'header already sent', e.message
  61
+      end
43 62
     end
44 63
   end
45 64
 end

0 notes on commit 06c9e17

Please sign in to comment.
Something went wrong with that request. Please try again.