class Translatomatic::HTTP::Request

HTTP request wrapper for Net::HTTP functionality

Attributes

body[RW]

@return [String] the HTTP body

method[R]

@return [String] the HTTP method

multipart_boundary[RW]

@return [String] the text to use to denote multipart boundaries. By

default, a random hexadecimal string is used.
uri[R]

@return [URI] the URI of the request

Public Class Methods

new(method, url, options = {}) click to toggle source

@param method [Symbol] HTTP method @param url [String,URI] URL of the request @return [Translatomatic::HTTPRequest] Create a new request

# File lib/translatomatic/http/request.rb, line 25
def initialize(method, url, options = {})
  @method = method
  @options = options
  @uri = url.respond_to?(:host) ? url.dup : URI.parse(url)
  query = options[:query]
  @uri.query = URI.encode_www_form(query) if query
  @multipart_boundary = generate_multipart_boundary
  @body = @options[:body]
end

Public Instance Methods

http_request() click to toggle source

@return [Object] The request object for use with Net::HTTP

# File lib/translatomatic/http/request.rb, line 36
def http_request
  @request ||= create_request
end

Private Instance Methods

create_request() click to toggle source
# File lib/translatomatic/http/request.rb, line 60
def create_request
  klass = Net::HTTP.const_get(@method.to_s.classify)
  request = klass.new(@uri)
  request['User-Agent'] = USER_AGENT

  (@options[:headers] || {}).each do |key, value|
    request[key] = value
  end

  request['Cookie'] = @options[:cookies] if @options[:cookies]

  content_type = @options[:content_type]

  if body
    if @options[:multipart] || body.is_a?(Array)
      boundary = "boundary=#{@multipart_boundary}"
      content_type = 'multipart/form-data; ' + boundary
      request.body = multipartify(body)
    elsif body.is_a?(Hash)
      # set_form_data does url encoding
      request.set_form_data(body)
    else
      request.body = body
    end
  end

  request.content_type = content_type if content_type
  request
end
generate_multipart_boundary() click to toggle source
# File lib/translatomatic/http/request.rb, line 42
def generate_multipart_boundary
  SecureRandom.hex(16)
end
multipartify(parts) click to toggle source
# File lib/translatomatic/http/request.rb, line 46
def multipartify(parts)
  string_parts = parts.collect do |i|
    part = paramify(i)
    '--' + @multipart_boundary + "\r\n" + part.to_s
  end
  string_parts.join('') + '--' + @multipart_boundary + "--\r\n"
end
paramify(object) click to toggle source
# File lib/translatomatic/http/request.rb, line 54
def paramify(object)
  return object if object.is_a?(Param) || object.is_a?(FileParam)
  raise 'invalid multipart parameter' unless object.is_a?(Hash)
  object[:filename] ? FileParam.new(object) : Param.new(object)
end