Class: RestDSL::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/rest_dsl/client.rb

Class Attribute Summary collapse

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(environment = nil, base_url: nil) ⇒ Client

Returns a new instance of Client.



20
21
22
23
24
25
26
27
28
29
30
# File 'lib/rest_dsl/client.rb', line 20

def initialize(environment = nil, base_url: nil)
  if base_url
    @base_url = base_url
  else
    environment = environment.to_sym
    environmental_info = environments.fetch(environment) do
      raise RestDSL::UndefinedEnvironmentError.new(environment, environments)
    end
    @base_url = "#{environmental_info[:url]}"
  end
end

Class Attribute Details

.config_dirObject

Returns the value of attribute config_dir.



10
11
12
# File 'lib/rest_dsl/client.rb', line 10

def config_dir
  @config_dir
end

Instance Attribute Details

#base_urlObject

Returns the value of attribute base_url.



18
19
20
# File 'lib/rest_dsl/client.rb', line 18

def base_url
  @base_url
end

Class Method Details

.default_headersObject



57
58
59
# File 'lib/rest_dsl/client.rb', line 57

def self.default_headers
  { accept: 'application/json' }
end

.environmentsObject



12
13
14
# File 'lib/rest_dsl/client.rb', line 12

def environments
  RestDSL.configuration[:environments]
end

Instance Method Details

#environmentsObject



53
54
55
# File 'lib/rest_dsl/client.rb', line 53

def environments
  self.class.environments
end

#execute(method, endpoint, headers, payload: nil, **hash_args, &block) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/rest_dsl/client.rb', line 32

def execute(method, endpoint, headers, payload: nil, **hash_args, &block)
  url = "#{@base_url}/#{endpoint}"
  args = { method: method.to_sym, url: Addressable::URI.escape(url), headers: headers }
  args.merge!(payload: payload) if payload && method_has_payload?(method)
  args.merge!(hash_args)

  response =
    begin
      RestClient::Request.new(args).execute(&block)
    rescue RestClient::ExceptionWithResponse => e
      e.response
    end
  { response: response, parsed: JSON.parse(response.to_s, symbolize_names: true) }
rescue JSON::ParserError => e
  { response: response, parsed: "Failed to parse, see response for more information, code was: #{response.code}, message was: #{response.body}" }
end

#method_has_payload?(method) ⇒ Boolean

Returns:

  • (Boolean)


49
50
51
# File 'lib/rest_dsl/client.rb', line 49

def method_has_payload?(method)
  Net::HTTP.const_get(:"#{method.to_s.capitalize}")::REQUEST_HAS_BODY
end