module MailPlugger

Constants

VERSION

Attributes

client[R]
delivery_options[R]
delivery_settings[R]
delivery_systems[R]

Public Class Methods

plug_in(delivery_system) { |self| ... } click to toggle source

Plug in SMTP(s) or defined API(s) class.

@param [String/Symbol] delivery_system the name of the SMTP/API

@example using Rails `config/initializers/mail_plugger.rb`

# Using SMTP:

MailPlugger.plug_in('smtp_client') do |smtp|
  smtp.delivery_settings = {
    smtp_settings: {
      address: 'smtp.server.com',
      port: 587,
      domain: 'test.domain.com',
      enable_starttls_auto: true,
      user_name: 'test_user',
      password: '1234',
      authentication: :plain
    }
  }
end

# Using API:

# The defined API class should have an 'initialize' and a 'deliver'
# method.
class DefinedApiClientClass
  def initialize(options = {})
    @settings = { api_key: '12345' }
    @options = options
  end

  def deliver
    API.new(@settings).client.post(generate_mail_hash)
  end

  private

  def generate_mail_hash
    {
      to: generate_recipients,
      from: {
        email: @options[:from].first
      },
      subject: @options[:subject],
      content: [
        {
          type: 'text/plain',
          value: @options[:text_part]
        },
        {
          type: 'text/html; charset=UTF-8',
          value: @options[:html_part]
        }
      ]
    }
  end

  def generate_recipients
    @options[:to].map do |to|
      {
        email: to
      }
    end
  end
end

MailPlugger.plug_in('defined_api') do |api|
  # It will search these options in the Mail::Message object
  api.delivery_options = [:to, :from, :subject, :text_part, :html_part]
  api.delivery_settings = { return_response: true }
  api.client = DefinedApiClientClass
end
# File lib/mail_plugger.rb, line 95
def plug_in(delivery_system)
  check_value(delivery_system)

  @delivery_system = delivery_system
  (@delivery_systems ||= []) << delivery_system

  yield self
rescue NoMethodError => e
  raise Error::WrongPlugInOption, e.message
end

Private Class Methods

check_value(delivery_system) click to toggle source

Check 'delivery_system' is valid or not. If it's not valid then it will raise an error.

@param [String/Symbol] delivery_system the name of the SMTP/API

# File lib/mail_plugger.rb, line 123
def check_value(delivery_system)
  if delivery_system.nil?
    raise Error::WrongDeliverySystem, '"delivery_system" is nil'
  end

  if delivery_system.is_a?(String) && delivery_system.strip.empty?
    raise Error::WrongDeliverySystem, '"delivery_system" is empty'
  end

  return if delivery_system.is_a?(String) || delivery_system.is_a?(Symbol)

  raise Error::WrongDeliverySystem, '"delivery_system" does not a ' \
    'String or Symbol'
end