Class: MsTeams::Message

Inherits:
Object
  • Object
show all
Defined in:
lib/ms_teams/message.rb

Defined Under Namespace

Classes: FailedRequest

Constant Summary collapse

REQUIRED_FIELDS =

Necessary fields to successfully send a message

%w(text url).freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(&block) {|@builder| ... } ⇒ Message

Initializes Team::Messages and builds an OpenStruct object

from a required block containing arbitrary values
and validates that the required fields are present

Parameters:

  • block (Proc)

Yields:


17
18
19
20
21
# File 'lib/ms_teams/message.rb', line 17

def initialize( &block )
  @builder = OpenStruct.new
  yield @builder
  validate
end

Instance Attribute Details

#builderObject

Returns the value of attribute builder


11
12
13
# File 'lib/ms_teams/message.rb', line 11

def builder
  @builder
end

Instance Method Details

#sendObject

POSTs a message to the url.

If the response is not successful it raises
a MsTeams::Message::FailedRequest error

28
29
30
31
32
33
34
35
36
37
# File 'lib/ms_teams/message.rb', line 28

def send
  uri = URI.parse( @builder.url )
  http = Net::HTTP.new( uri.host, uri.port )
  http.use_ssl = true
  response = http.post( uri.path, @builder.to_h.to_json, "Content-Type": "application/json" )
  unless successful_response?( response )
    raise FailedRequest, "Unable to send message successfully. Response code `#{response.code}`"
  end
  response
end

#validateObject

Ensures that the required fields are present

Raises an ArgumentError if the required fields are not present.

42
43
44
45
46
47
48
# File 'lib/ms_teams/message.rb', line 42

def validate
  REQUIRED_FIELDS.each do |field|
    error( field ) if @builder[field].nil? || @builder[field].empty?
  end

  true
end