Sha256: 86d3d94f45436d229a3ecb771da0fd134fefd0b852954f337c54a808dc43968d

Contents?: true

Size: 1.4 KB

Versions: 2

Compression:

Stored size: 1.4 KB

Contents

module Mailstro
  class Delivery
    require 'net/http'
    require 'openssl'
    require 'json'

    attr_reader :template, :recipient, :payload

    def self.deliver(*args)
      new(*args).deliver
    end

    def initialize(template, options)
      @template  = template
      @recipient = options[:recipient]
      @payload   = options[:payload]
    end

    def deliver
      http             = Net::HTTP.new(endpoint_uri.host, endpoint_uri.port)
      http.use_ssl     = endpoint_uri.scheme == "https"
      http.verify_mode = OpenSSL::SSL::VERIFY_NONE

      request      = Net::HTTP::Post.new(endpoint_uri.request_uri, { 'Content-Type' =>'application/json' })
      request.body = JSON.generate(post_data)

      response = http.request(request)

      # response.status
      # response["header-here"] # All headers are lowercase

      JSON.parse(response.body)
    end

    private

    def post_data
      { 'template' => template,
        'recipient' => recipient,
        'api_key' => Mailstro.configuration.api_key }.tap do |payload|
        if self.payload.kind_of?(Hash)
          payload['payload'] = self.payload
        end
      end
    end

    def endpoint_uri
      @endpoint_uri ||= URI.parse(endpoint)
    end

    def endpoint
      (Mailstro.configuration.use_ssl ? "https://" : "http://") +
        "#{Mailstro.configuration.endpoint}/v#{Mailstro.configuration.api_version}/postman"
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
mailstro-0.0.2 lib/mailstro/delivery.rb
mailstro-0.0.1 lib/mailstro/delivery.rb