Sha256: 52c5b68536bedc060b10b952b2fd8dc6d830bf8b6a10440a1901626160a5de54

Contents?: true

Size: 1.62 KB

Versions: 1

Compression:

Stored size: 1.62 KB

Contents

# frozen_string_literal: true

require 'slack-notifier'

module DeviseSlackNotifiable
  class Notifier
    def initialize
      return unless enabled?

      raise DeviseSlackNotifiable::Errors::Configuration, 'Missing Slack Webhook URL' unless webhook

      @client = Slack::Notifier.new(webhook)
    end

    # Sends slack message
    #
    # @param [Model] entity
    # @param [Proc] message_formatter
    def send_message(entity, message_formatter)
      return true unless enabled?

      @client.ping(
        formatter(
          message_formatter.call(entity),
          entity
        )
      )
    end

    protected

    attr_reader :client

    def enabled?
      DeviseSlackNotifiable.configuration.enabled
    end

    def webhook
      DeviseSlackNotifiable.configuration.slack_webhook
    end

    def context_fields
      DeviseSlackNotifiable.configuration.context_fields
    end

    def formatter(message, entity)
      {
        blocks: [
          {
            type: 'section',
            text: {
              type: 'plain_text',
              text: message,
              emoji: true
            }
          },
          {
            type: 'divider'
          },
          {
            type: 'section',
            text: {
              type: 'plain_text',
              text: 'Context:',
              emoji: true
            }
          },
          {
            type: 'section',
            fields: context_fields.map do |field|
              {
                type: 'mrkdwn',
                text: "*#{field.to_s.humanize}:* #{entity.send(field)}"
              }
            end
          }
        ]
      }
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
devise_slack_notifiable-0.1.0 lib/devise_slack_notifiable/notifier.rb