Class: RestfulSharePoint::Connection

Inherits:
Object
  • Object
show all
Defined in:
lib/restful-sharepoint/connection.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(site_url, username = nil, password = nil) ⇒ Connection

Returns a new instance of Connection.



6
7
8
9
10
# File 'lib/restful-sharepoint/connection.rb', line 6

def initialize(site_url, username = nil, password = nil)
  @site_url = site_url
  @username = username
  @password = password
end

Instance Attribute Details

#site_urlObject (readonly)

Returns the value of attribute site_url.



12
13
14
# File 'lib/restful-sharepoint/connection.rb', line 12

def site_url
  @site_url
end

Instance Method Details

#get(path, options: {}) ⇒ Object



14
15
16
# File 'lib/restful-sharepoint/connection.rb', line 14

def get(path, options: {})
  request path, :get, options: options
end

#request(path, method, options: {}, body: nil) {|request| ... } ⇒ Object

Path can be either relative to the site URL, or a complete URL itself. Takes an optional ‘options` hash which are any number of valid OData query options (dollar sign prefix is added automatically) Also takes an optional block that is provided the HTTPI::Request instance, allowing customisation of the request.

Yields:



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/restful-sharepoint/connection.rb', line 21

def request(path, method, options: {}, body: nil)
  url = URI.parse(path).is_a?(URI::HTTP) ? path : "#{@site_url}#{path}"
  options_str = options.map { |k,v| "$#{k}=#{CGI.escape v.to_s}" }.join('&')
  url += "?#{options_str}"
  req = HTTPI::Request.new(url: url, headers: {'accept' => 'application/json; odata=verbose'})
  req.auth.ntlm(@username, @password) if @username
  if body
    req.body = body.to_json.gsub('/', '\\/') # SharePoint requires forward slashes be escaped in JSON (WTF!!!)
    req.headers['Content-Type'] = 'application/json'
    req.headers['X-HTTP-Method'] = 'MERGE' # TODO: Extend logic to support all operations
    req.headers['If-Match'] = '*'
  end
  yield(request) if block_given?
  response = HTTPI.request(method, req)
  if response.body.empty?
    if response.code >= 300
      raise RestError, "Server returned HTTP status #{response.code} with no message body."
    end
  else
    if response.headers['Content-Type'].start_with? "application/json"
      data_tree = parse(response.body)
    else
      response.body
    end
  end
end