Sha256: 1f5071ca6ceb5a90604fe0cb4f852832a3d42cb4139dad7462a5d902724e4169

Contents?: true

Size: 1.3 KB

Versions: 2

Compression:

Stored size: 1.3 KB

Contents

module SendGridMailer
  class Deliverer
    attr_accessor :settings

    def initialize(settings)
      self.settings = settings.merge(return_response: true)
    end

    def api_key
      settings[:api_key] || raise(SendGridMailer::Exception.new("Missing sendgrid API key"))
    end

    def deliver!(msg)
      set_template_id_from_name(msg.sg_definition)
      logger = SendGridMailer::Logger.new(msg.sg_definition)
      logger.log_definition
      response = sg_api.client.mail._('send').post(request_body: msg.sg_definition.to_json)
      logger.log_result(response)
      response
    end

    private

    def set_template_id_from_name(definition)
      return unless definition.template_name
      response = sg_api.client.templates.get

      if response.status_code != "200"
        m = "Error trying to get templates. Status Code: #{response.status_code}"
        raise SendGridMailer::Exception.new(m)
      end

      JSON.parse(response.body)["templates"].each do |tpl|
        definition.set_template_id(tpl["id"]) if tpl["name"] == definition.template_name
      end

      if !definition.template_id?
        m = "No template with name #{definition.template_name}"
        raise SendGridMailer::Exception.new(m)
      end
    end

    def sg_api
      @sg_api ||= SendGrid::API.new(api_key: api_key)
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
send_grid_mailer-0.5.0 lib/send_grid_mailer/deliverer.rb
send_grid_mailer-0.4.0 lib/send_grid_mailer/deliverer.rb