Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
Help us understand the problem. What is going on with this article?

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

More than 1 year has passed since last update.

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

https://github.com/stevenosloan/slack-notifier

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)
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away