Class: RackMotion::URLProtocol

Inherits:
NSURLProtocol
  • Object
show all
Defined in:
lib/project/RackMotion.rb

Constant Summary collapse

@@middlewares =
[]
@@app =
nil

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.appObject



30
31
32
# File 'lib/project/RackMotion.rb', line 30

def self.app
  @@app
end

.app=(obj) ⇒ Object



34
35
36
# File 'lib/project/RackMotion.rb', line 34

def self.app=(obj)
  @@app = obj
end

.canInitWithRequest(request) ⇒ Object



38
39
40
41
42
# File 'lib/project/RackMotion.rb', line 38

def self.canInitWithRequest(request)
  return false unless request.URL
  return false unless request.URL.scheme.start_with?("http")
  !NSURLProtocol.propertyForKey('RackMotion', inRequest: request) 
end

.canonicalRequestForRequest(request) ⇒ Object



44
45
46
# File 'lib/project/RackMotion.rb', line 44

def self.canonicalRequestForRequest(request)
  return request
end

.middlewaresObject



22
23
24
# File 'lib/project/RackMotion.rb', line 22

def self.middlewares
  @@middlewares
end

.middlewares=(obj) ⇒ Object



26
27
28
# File 'lib/project/RackMotion.rb', line 26

def self.middlewares=(obj)
  @@middlewares = obj
end

Instance Method Details

#call(new_request) ⇒ Object



72
73
74
75
76
77
78
79
80
81
82
# File 'lib/project/RackMotion.rb', line 72

def call(new_request)
  NSURLProtocol.setProperty(true, forKey: 'RackMotion', inRequest: new_request) 

  connection_delegate = ConnectionDelegate.new

  @connection = NSURLConnection.alloc.initWithRequest(new_request, delegate: connection_delegate, startImmediately: true)
  NSRunLoop.currentRunLoop.run

  connection_delegate.semaphore.wait
  return connection_delegate.response.statusCode, connection_delegate.response.allHeaderFields.mutableCopy, connection_delegate.data
end

#startLoadingObject



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/project/RackMotion.rb', line 48

def startLoading
  @thread = NSThread.alloc.initWithTarget(lambda do

    chain = @@middlewares.inject(@@app ? @@app : self) do |instance, klass|
      klass.new(instance)
    end

    status, headers, data = chain.call self.request.mutableCopy

    response = NSHTTPURLResponse.alloc.initWithURL self.request.URL, statusCode: status, HTTPVersion: 'HTTP/1.1', headerFields: headers

    self.client.URLProtocol(self, didReceiveResponse: response, cacheStoragePolicy: NSURLCacheStorageNotAllowed)
    self.client.URLProtocol(self, didLoadData: data)
    self.client.URLProtocolDidFinishLoading(self)
  end, selector: 'call', object: nil)

  @thread.start
end

#stopLoadingObject



67
68
69
70
# File 'lib/project/RackMotion.rb', line 67

def stopLoading
  @connection.cancel if @connection
  @thread.cancel if @thread
end