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.



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

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

.methods_without_payloadsObject

Returns the value of attribute methods_without_payloads.



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

def methods_without_payloads
  @methods_without_payloads
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



59
60
61
# File 'lib/rest_dsl/client.rb', line 59

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



55
56
57
# File 'lib/rest_dsl/client.rb', line 55

def environments
  self.class.environments
end

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



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

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)


51
52
53
# File 'lib/rest_dsl/client.rb', line 51

def method_has_payload?(method)
  !self.class.methods_without_payloads.include?(method)
end