http_caller.rb revision 61ca03fc1ce689310740e8ae71fdaa533d2ba1bc
0cb2e8eb55e70f8ebe1e8349bdf49e4cbe5d8834Timo Sirainen attr_accessor :previous_response, :current_response
0cb2e8eb55e70f8ebe1e8349bdf49e4cbe5d8834Timo Sirainen attr_accessor :content_test_block, :write_file, :file_type
0cb2e8eb55e70f8ebe1e8349bdf49e4cbe5d8834Timo Sirainen def initialize(uri, data: {}, redirect_limit: DEFAULT_REDIRECTS)
f16c114c20bbd7d292d93415d1e56c8dd6abd3e7Timo Sirainen # Currently only File and Tempfile are
f16c114c20bbd7d292d93415d1e56c8dd6abd3e7Timo Sirainen # allowed for file_type.
f16c114c20bbd7d292d93415d1e56c8dd6abd3e7Timo Sirainen make_http_request(URI(uri)) { |r| result = handle_response(r) }
8fcff4c5b52f24d9c681805fdf06b486f1d0fcbeTimo Sirainen raise TooManyRedirectionsError.new(last_response: previous_response)
f7d43647acc6dc80064c8c4cacf5bf86f754c530Timo SirainenCan't follow the response from #{uri} anymore.
98c1cf256927e254f0c092acd2ddcd7ea50bd009Timo Sirainen raise UnfollowableResponseError.new(msg, last_response: response)
a2637488c8d514ec1ac3914811deee814f9761b3Timo Sirainen self.redirect_limit -= 1
a2637488c8d514ec1ac3914811deee814f9761b3Timo Sirainen self.previous_response = current_response
a2637488c8d514ec1ac3914811deee814f9761b3Timo Sirainen call(write_file: write_file, file_type: file_type)
a2637488c8d514ec1ac3914811deee814f9761b3Timo Sirainen def is_redirection?(response)
a2637488c8d514ec1ac3914811deee814f9761b3Timo Sirainen response['location'] && !response['location'].empty?
ca98892a6b8a30ffc1fe26fcf02c7d59e3204e7eTimo Sirainen def has_actual_content?(response)
a2637488c8d514ec1ac3914811deee814f9761b3Timo Sirainen if self.content_test_block
a2637488c8d514ec1ac3914811deee814f9761b3Timo Sirainen content_test_block.call(response)
a2637488c8d514ec1ac3914811deee814f9761b3Timo Sirainen response.is_a?(Net::HTTPSuccess) &&
1d2b188f0eedc3cab6e27ceac5425a037f38042eTimo Sirainen response.content_type != 'text/html'
a2637488c8d514ec1ac3914811deee814f9761b3Timo Sirainen def provide_io
a2637488c8d514ec1ac3914811deee814f9761b3Timo Sirainen if write_file
02b79f9c2636da1829eee5b92753602bba8b67edTimo Sirainen if file_type == File
02b79f9c2636da1829eee5b92753602bba8b67edTimo Sirainen file_type.new(write_file, 'w+')
02b79f9c2636da1829eee5b92753602bba8b67edTimo Sirainen elsif file_type == Tempfile
a2637488c8d514ec1ac3914811deee814f9761b3Timo Sirainen file_type.new('uri-fetcher')
02b79f9c2636da1829eee5b92753602bba8b67edTimo Sirainen def provide_result(response)
a2637488c8d514ec1ac3914811deee814f9761b3Timo Sirainen io = provide_io
299183fbb6ec5d0828a0880da372540421ac4665Timo Sirainen response.read_body { |chunk| io << chunk }
299183fbb6ec5d0828a0880da372540421ac4665Timo Sirainen io.rewind if io.respond_to?(:rewind)
299183fbb6ec5d0828a0880da372540421ac4665Timo Sirainen def data_json
299183fbb6ec5d0828a0880da372540421ac4665Timo Sirainen (data || {}).to_json