22
33module SendGrid
44 class Client
5- attr_accessor :api_user , :api_key , :protocol , :host , :port , :url , :endpoint , :user_agent
5+ attr_accessor :api_user , :api_key , :protocol , :host , :port , :url , :endpoint ,
6+ :user_agent
67 attr_writer :adapter , :conn
78
89 def initialize ( params = { } )
@@ -11,38 +12,42 @@ def initialize(params = {})
1112 self . protocol = params . fetch ( :protocol , 'https' )
1213 self . host = params . fetch ( :host , 'api.sendgrid.com' )
1314 self . port = params . fetch ( :port , nil )
14- self . url = params . fetch ( :url , self . protocol + '://' + self . host + ( self . port ? ":#{ self . port } " : '' ) )
15+ self . url = params . fetch ( :url , protocol + '://' + host + ( port ? ":#{ port } " : '' ) )
1516 self . endpoint = params . fetch ( :endpoint , '/api/mail.send.json' )
16- self . adapter = params . fetch ( :adapter , self . adapter )
17- self . conn = params . fetch ( :conn , self . conn )
17+ self . adapter = params . fetch ( :adapter , adapter )
18+ self . conn = params . fetch ( :conn , conn )
1819 self . user_agent = params . fetch ( :user_agent , "sendgrid/#{ SendGrid ::VERSION } ;ruby" )
1920 yield self if block_given?
2021 end
2122
2223 def send ( mail )
23- res = self . conn . post do |req |
24+ res = conn . post do |req |
2425 payload = mail . to_h
2526
26- req . url ( self . endpoint )
27+ req . url ( endpoint )
2728
2829 # Check if using username + password or API key
29- if self . api_user
30+ if api_user
3031 # Username + password
31- payload . merge ( { api_user : self . api_user , api_key : self . api_key } )
32+ payload = payload . merge ( api_user : api_user , api_key : api_key )
3233 else
3334 # API key
34- req . headers [ 'Authorization' ] = "Bearer #{ self . api_key } "
35+ req . headers [ 'Authorization' ] = "Bearer #{ api_key } "
3536 end
3637
3738 req . body = payload
3839 end
40+
41+ fail SendGrid ::Exception , res . body if res . status != 200
42+
43+ SendGrid ::Response . new ( code : res . status , headers : res . headers , body : res . body )
3944 end
4045
4146 def conn
42- @conn ||= Faraday . new ( url : self . url ) do |conn |
47+ @conn ||= Faraday . new ( url : url ) do |conn |
4348 conn . request :multipart
4449 conn . request :url_encoded
45- conn . adapter self . adapter
50+ conn . adapter adapter
4651 end
4752 end
4853
0 commit comments