Sha256: e501d69c40701245a95b552800bb36be1d21e575c9c92776d3dd799581f3f105

Contents?: true

Size: 1.69 KB

Versions: 1

Compression:

Stored size: 1.69 KB

Contents

module Griddler
  module Mailgun
    class Adapter
      def initialize(params)
        @params = params
      end

      def self.normalize_params(params)
        adapter = new(params)
        adapter.normalize_params
      end

      def normalize_params
        {
          to: to_recipients,
          cc: cc_recipients,
          from: determine_sender,
          subject: params[:subject],
          text: params['body-plain'],
          html: params['body-html'],
          attachments: attachment_files,
          headers: headers
        }
      end

      private

      attr_reader :params

      def determine_sender
        sender = param_or_header(:From)
        sender ||= params[:sender]
      end

      def to_recipients
        to_emails = param_or_header(:To)
        to_emails ||= params[:recipient]
        to_emails.split(',').map(&:strip)
      end

      def cc_recipients
        cc = param_or_header(:Cc)
        cc.split(',').map(&:strip)
      end

      def headers
        @headers ||= extract_headers
      end

      def extract_headers
        return nil unless params['message-headers']

        extracted_headers = {}
        parsed_headers = JSON.parse(params['message-headers'])
        parsed_headers.each{ |h| extracted_headers[h[0]] = h[1] }
        ActiveSupport::HashWithIndifferentAccess.new(extracted_headers)
      end

      def param_or_header(key)
        if params[key].present?
          params[key]
        else
          headers[key]
        end
      end

      def attachment_files
        attachment_count = params['attachment-count'].to_i

        attachment_count.times.map do |index|
          params.delete("attachment-#{index+1}")
        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
griddler-mailgun-1.0.0 lib/griddler/mailgun/adapter.rb