class UnderOs::HTTP::Request

A little wrap to handle iOS HTTP requests receiving

Options:

* :method   - GET, POST, ...
* :cookies  - Hash of cookie values
* :stream   - boolean, in case you want to stream stuff
* :params   - the POST/PUT/PATCH params hash
* :encoding - the POST data encoding

Events:

* :response - when response header is received
* :data     - when a chunk of data is received
* :success  - when the request is successfully finished
* :failure  - when request has failed for whatever reason
* :complete - when it's complete (either way)

Attributes

method[R]
params[R]
url[R]

Public Class Methods

new(url, options={}, &block) click to toggle source
# File lib/under_os/http/request.rb, line 23
def initialize(url, options={}, &block)
  @url     = url
  @options = options

  on :complete, &block if block_given?
end

Public Instance Methods

cancel() click to toggle source
# File lib/under_os/http/request.rb, line 46
def cancel
  @connection.cancel

  return self
end
cookies() click to toggle source
# File lib/under_os/http/request.rb, line 63
def cookies
  @options[:cookies] || {}
end
encoding() click to toggle source
# File lib/under_os/http/request.rb, line 71
def encoding
  @options[:encoding] || 'utf-8'
end
headers() click to toggle source
# File lib/under_os/http/request.rb, line 59
def headers
  @options[:headers] || {}
end
on(*args, &block) click to toggle source
Calls superclass method
# File lib/under_os/http/request.rb, line 30
def on(*args, &block)
  super *args do |event|
    args = block.arity == 0 ? [] : [event.params[:response]]
    block.call *args
  end
end
send() click to toggle source
# File lib/under_os/http/request.rb, line 37
def send
  @request    = build_request
  @receiver   = Receiver.new(self, @options[:stream])
  @connection = NSURLConnection.alloc.initWithRequest(@request, delegate:@receiver)
  @connection.start

  return self
end

Protected Instance Methods

build_request() click to toggle source
# File lib/under_os/http/request.rb, line 77
def build_request
  query = params.to_query
  url   = build_url(query)

  NSMutableURLRequest.requestWithURL(url).tap do |request|
    request.setHTTPMethod method

    headers.merge(UnderOs::HTTP::Cookies.new(cookies, url).headers).each do |key, value|
      request.addValue value, forHTTPHeaderField:key
    end

    if %w[POST PUT PATCH DELETE].include?(method) && !query.empty?
      request.addValue "application/x-www-form-urlencoded;charset=#{encoding}", forHTTPHeaderField:"Content-Type"
      request.setHTTPBody query.to_data(encoding)
    end
  end
end
build_url(query) click to toggle source
# File lib/under_os/http/request.rb, line 95
def build_url(query)
  url  = @url

  if method == "GET" && !query.empty?
    url += url.include?('?') ? '&' : '?'
    url += query
  end

  NSURL.URLWithString(url)
end