opal/opal-jquery/http.rb in opal-jquery-0.2.0 vs opal/opal-jquery/http.rb in opal-jquery-0.3.0.beta1
- old
+ new
@@ -1,27 +1,64 @@
require 'json'
require 'native'
+require 'promise'
+require 'opal-jquery/constants'
class HTTP
+ `var $ = #{JQUERY_SELECTOR.to_n}` # cache $ for SPEED
+
+ def self.setup
+ Hash.new(`$.ajaxSetup()`)
+ end
+
+ def self.setup= settings
+ `$.ajaxSetup(#{settings.to_n})`
+ end
+
+
attr_reader :body, :error_message, :method, :status_code, :url, :xhr
def self.get(url, opts={}, &block)
- self.new(url, :GET, opts, block).send!
+ build_request url, :GET, opts, block
end
def self.post(url, opts={}, &block)
- self.new(url, :POST, opts, block).send!
+ build_request url, :POST, opts, block
end
def self.put(url, opts={}, &block)
- self.new(url, :PUT, opts, block).send!
+ build_request url, :PUT, opts, block
end
def self.delete(url, opts={}, &block)
- self.new(url, :DELETE, opts, block).send!
+ build_request url, :DELETE, opts, block
end
+ def self.patch(url, opts={}, &block)
+ build_request url, :PATCH, opts, block
+ end
+
+ def self.head(url, opts={}, &block)
+ build_request url, :HEAD, opts, block
+ end
+
+ def self.build_request(url, method, options, block)
+ unless block
+ promise = ::Promise.new
+ block = proc do |response|
+ if response.ok?
+ promise.resolve response
+ else
+ promise.reject response
+ end
+ end
+ end
+
+ http = new(url, method, options, block).send!
+ promise || http
+ end
+
def initialize(url, method, options, handler=nil)
@url = url
@method = method
@ok = true
@xhr = nil
@@ -65,19 +102,9 @@
return #{ http.fail };
};
}
@settings = settings
- end
-
- def callback(&block)
- @callback = block
- self
- end
-
- def errback(&block)
- @errback = block
- self
end
def fail
@ok = false
@errback.call self if @errback