DEV Community

Cover image for Sending Slack notifications with Ruby on Rails
Oksana Ivanchenko
Oksana Ivanchenko

Posted on

Sending Slack notifications with Ruby on Rails

In my latest article I showed you how to integrate Stripe on Ruby on Rails. Today I'm writing a quick tutorial about how to get Slack notification every time someone makes a purchase on your site. It's very easy and simple. I chose Slack notification because as for me this platform is the best to share short messages instantly with your collaborators.

For the first part the Slack tutorial is quite explicite, so I suggest you to read it and do what they say. Firstly you need to create a Slack app, then activate Incoming Webhooks and choose a channel to post your notifications. After doing the Slack tutorial, navigate to the page of your app => Features => Incoming Webhooks and you should see something like this:

alt text

Now, go to your Ruby on Rails application and in the terminal open the nano editor to add the Webhook URL in encrypted rails credentials:

$ EDITOR=nano rails credentials:edit

In the editor, add:

   token: ''

Use Ctrl+X to exit editor.

Now in our Gemfile add a new gem:

gem 'slack-notifier'

Then, run the command 'bundle install' in the terminal to install it. Now, in config/initializers create slack_notifier.rb:

module SlackNotifier
  CLIENT = Rails.application.credentials.slack[:token]

Finally, the last step is to send the notification. I want that every time someone pays I get a notification on slack. So we need to add this message in the action that subscribes the user to a plan. If you followed my previous tutorial it will be in the action subscribe inΒ the view views/controllers/billing_controller.rb:

def subscribe
    #code which you can see in my previous tutorial "πŸ’Έ Boom! New purchase for #{[0].plan.amount / 100}€ from #{}! πŸ’Έ"

Now I also want to have a notification when a user registers. In order to do it we go to app/models/user.rb:

after_create :notify_slack

  def notify_slack "πŸŽ‰ New user: #{email} πŸŽ‰"

Now we are going to test if everything works well. So we are going on our application, create a new user and subscribe him to one of the plans. You should get 2 notifications which look something like this:
alt text

That's it! I hope you will see this notifications very often!

Discussion (1)

tracyloisel profile image

I reviewed the code of this gem and it's a bit old. Last main update was 3 years ago. What do you think ?