Class: Locomotive::Httparty::Webservice

Inherits:
Object
  • Object
show all
Includes:
HTTParty
Defined in:
lib/locomotive/httparty/webservice.rb

Class Method Summary collapse

Class Method Details

.consume(url, options = {}) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/locomotive/httparty/webservice.rb', line 9

def self.consume(url, options = {})
  options[:method] = :get if options[:method].nil?

  options.delete(:format) if options[:format] == 'default'

  path = extract_path(url, options)

  # auth ?
  username, password = options.delete(:username), options.delete(:password)
  options[:basic_auth] = { username: username, password: password } if username

  self.perform_request_to(path, options)
end

.extract_path(url, options) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/locomotive/httparty/webservice.rb', line 23

def self.extract_path(url, options)
  url     = HTTParty.normalize_base_uri(url)
  uri     = URI.parse(url)
  params  = Rack::Utils.parse_nested_query(uri.query)

  key = options[:method].to_sym == :post ? :body : :query
  options[key] = params unless params.blank?

  (uri.path.blank? ? '/' : uri.path).tap do
    uri.query = nil; uri.path = ''
    options[:base_uri] = uri.to_s
  end
end

.perform_request_to(path, options) ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/locomotive/httparty/webservice.rb', line 37

def self.perform_request_to(path, options)
  # [DEBUG]
  # puts "[WebService] consuming #{path}, #{options.inspect}"

  # sanitize the options
  options[:format]  = options[:format].gsub(/[\'\"]/, '').to_sym if options.has_key?(:format)
  options[:headers] = { 'User-Agent' => 'LocomotiveCMS' } if options[:with_user_agent]

  response        = self.send(options.delete(:method), path, options)
  parsed_response = response.parsed_response

  if response.code == 200
    if parsed_response.respond_to?(:underscore_keys)
      parsed_response.underscore_keys
    else
      parsed_response.collect(&:underscore_keys)
    end
  else
    nil
  end
end