LoginSignup
1
0

More than 3 years have passed since last update.

【Rails】Slackへの通知をActionMailerのようなerbテンプレートを使う形で実装する

Posted at

以下のGemを利用してSlackで通知を実装する際ActionMailerのようにerbを使ってviewを分けられないかと検討した。

app/views/admin_slack_notifier/receive_message_from_user.text.erb
【<%= @subject %>】

■□–––––––––––––––––––––□■
▼送信者情報
<%= @message.user.name %>

▼送信内容
<%= @message.content %>

■□–––––––––––––––––––––□■

app/libs/slack_notifier.rb
module SlackNotifier
  CONFIG = YAML.load_file(Rails.root.join('config', 'slack.yml'))[Rails.env]

  class << self
    def post(to, text, options = {})
      options = options.symbolize_keys
      dry_run = options.key?(:dry_run) ? options[:dry_run] : CONFIG['dry_run']
      post_options = format_options(to, text, options)
      notifier = Slack::Notifier.new CONFIG['webhook_url']
      notifier.post post_options unless dry_run
    end

    private

    # rubocop:disable Metrics/AbcSize
    def format_options(to, text, options)
      post_options = {
        'channel' => (options[:channel].presence || CONFIG[to.to_s]['channel']),
        'icon_emoji' => (options[:icon_emoji].presence || CONFIG[to.to_s]['icon_emoji']),
        'username' => (options[:username].presence || CONFIG[to.to_s]['username']),
        'text' => text
      }
      post_options[:title] = options[:title] if options.key?(:title)
      post_options
    end
    # rubocop:enable Metrics/AbcSize
  end
end


app/libs/admin_slack_notifier.rb
module AdminSlackNotifier

  class << self

    def receive_message_from_user(message)
      @message = message
      @subject = 'ユーザーより新しいメッセージが送信されました'
      post_with_template 'admin_channel', __method__, binding
    end

    private

    def post_with_template(to, view_name, binding)
      erb = Rails.root.join('app', 'views', name.underscore, "#{view_name}.text.erb").read
      text = ERB.new(erb).result(binding)
      SlackNotifier.post to, text
    end
  end
end

config/slack.yml
development: &default
  dry_run: true
  username: &username Admin
  webhook_url: WEBHOOK_URL
  admin_channel:
    channel: admin_channel
    icon_emoji: ":crystal_ball:"
    username: *username
staging:
  <<: *default
  dry_run: false
production:
  <<: *default
  dry_run: false
test:
  <<: *default

以下のような形でAction名と同様のviewを習得してSlackの通知を送信することができる。

sample.rb
    AdminSlackNotifier.receive_message_from_user(message)
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0