Class: Crowbar::Client::Request::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/crowbar/client/request/base.rb

Overview

Base that provides methods shared between request implementations

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(attrs = {}) ⇒ Base

Returns a new instance of Base.



29
30
31
# File 'lib/crowbar/client/request/base.rb', line 29

def initialize(attrs = {})
  self.attrs = Hashie::Mash.new(attrs)
end

Instance Attribute Details

#attrsObject

Returns the value of attribute attrs.



27
28
29
# File 'lib/crowbar/client/request/base.rb', line 27

def attrs
  @attrs
end

#requestObject

Returns the value of attribute request.



26
27
28
# File 'lib/crowbar/client/request/base.rb', line 26

def request
  @request
end

Instance Method Details

#contentObject



37
38
39
# File 'lib/crowbar/client/request/base.rb', line 37

def content
  @content ||= {}
end

#headersObject



41
42
43
44
45
46
# File 'lib/crowbar/client/request/base.rb', line 41

def headers
  @headers ||= {
    "Content-Type" => "application/json",
    "Accept" => "application/json"
  }
end

#paramsObject



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

def params
  case method
  when :post
    [
      method,
      content
    ]
  when :put
    [
      method,
      content.to_json
    ]
  else
    [
      method
    ]
  end
end

#processObject



67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
# File 'lib/crowbar/client/request/base.rb', line 67

def process
  result = begin
    request.send(
      *params,
      accept: headers["Accept"],
      content_type: headers["Content-Type"]
    )
  rescue => e
    if e.class.superclass == RestClient::RequestFailed
      Hashie::Mash.new(
        parsed_response: {
          error: e.response
        },
        code: e.http_code
      )
    else
      raise e
    end
  end

  if block_given?
    yield result
  else
    result
  end
end