aboutsummaryrefslogtreecommitdiffstats
path: root/actionpack/lib/action_controller/rewindable_input.rb
blob: 058453ea68c1408e777c9fac5d0a77e5274e3d2f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
module ActionController
  class RewindableInput
    class RewindableIO < ActiveSupport::BasicObject
      def initialize(io)
        @io = io
      end

      def read(*args)
        read_original_io
        @io.read(*args)
      end

      def rewind
        read_original_io
        @io.rewind
      end

      def string
        @string
      end

      def method_missing(method, *args, &block)
        @io.send(method, *args, &block)
      end

      private
        def read_original_io
          unless @string
            @string = @io.read
            @io = StringIO.new(@string)
          end
        end
    end

    def initialize(app)
      @app = app
    end

    def call(env)
      env['rack.input'] = RewindableIO.new(env['rack.input'])
      @app.call(env)
    end
  end
end