Class: Fron::Request

Inherits:
Object show all
Defined in:
opal/fron/request/request.rb

Overview

Request

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(url, headers = {}) ⇒ Request

Initialies the request


12
13
14
15
16
17
18
# File 'opal/fron/request/request.rb', line 12

def initialize(url, headers = {})
  @url = url
  @headers = headers
  @request = `new XMLHttpRequest()`
  `#{@request}.addEventListener('readystatechange' , function(){#{handleStateChange}})`
  self
end

Instance Attribute Details

#headersObject

Returns the value of attribute headers


6
7
8
# File 'opal/fron/request/request.rb', line 6

def headers
  @headers
end

#urlObject

Returns the value of attribute url


6
7
8
# File 'opal/fron/request/request.rb', line 6

def url
  @url
end

Instance Method Details

#get(data) {|response| ... } ⇒ Object

Runs a GET request

Yield Parameters:


48
49
50
# File 'opal/fron/request/request.rb', line 48

def get(data, &callback)
  request 'GET', data, &callback
end

#handleStateChangeObject (private)

Handles the hash change


87
88
89
90
91
# File 'opal/fron/request/request.rb', line 87

def handleStateChange
  return unless readyState == 4
  response = Response.new `#{@request}.status`, `#{@request}.response`, `#{@request}.getAllResponseHeaders()`
  @callback.call response if @callback
end

#post(data) {|response| ... } ⇒ Object

Runs a POST request

Yield Parameters:


57
58
59
# File 'opal/fron/request/request.rb', line 57

def post(data, &callback)
  request 'POST', data, &callback
end

#put(data) {|response| ... } ⇒ Object

Runs a PUT request

Yield Parameters:


66
67
68
# File 'opal/fron/request/request.rb', line 66

def put(data, &callback)
  request 'PUT', data, &callback
end

#readyStateNumeric (private)

Returns the ready state of the request


82
83
84
# File 'opal/fron/request/request.rb', line 82

def readyState
  `#{@request}.readyState`
end

#request(method = 'GET', data = nil) {|response| ... } ⇒ Object

Runs a request

Yield Parameters:


26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'opal/fron/request/request.rb', line 26

def request(method = 'GET', data = nil, &callback)
  if readyState == 0 || readyState == 4
    @callback = callback
    if method.upcase == 'GET' && data
      `#{@request}.open(#{method},#{@url + '?' + data.toQueryString})`
      setHeaders
      `#{@request}.send()`
    else
      `#{@request}.open(#{method},#{@url})`
      setHeaders
      `#{@request}.send(#{data.to_json if data})`
    end
  else
    fail 'The request is already running!'
  end
end

#setHeadersObject (private)

Sets the headers


73
74
75
76
77
# File 'opal/fron/request/request.rb', line 73

def setHeaders
  @headers.each_pair do |header, value|
    `#{@request}.setRequestHeader(#{header},#{value})`
  end
end