How to receive and respond to text messages in Ruby with Hanami and Twilio
Tags: ruby, rails, hanami, twilio
Published: 2017-11-27 22:05:25

---
title: How to receive and respond to text messages in Ruby with Hanami and Twilio
published: true
description: If you’re building web applications with Ruby then you’re probably using Rails. Hanami is a young competitor focused on providing a full featured, modern web framework for Ruby developers that is fast, secure and flexible.
tags: ruby, rails, hanami, twilio
cover_image: https://thepracticaldev.s3.amazonaws.com/i/w0coeodbjwczj4sn6mmu.gif
canonical_url: https://www.twilio.com/blog/2017/11/how-to-receive-and-respond-to-text-messages-in-ruby-with-hanami-and-twilio.html
---

If you're building web applications with Ruby then you're probably using <a href="http://rubyonrails.org/">Rails</a>. <a href="http://hanamirb.org/">Hanami</a> is a young competitor focused on providing a full featured, modern web framework for Ruby developers that is fast, secure and flexible.

Hanami is a new web application framework for the Ruby community. It has been under development since 2014, <a href="http://hanamirb.org/blog/2016/01/22/lotus-is-now-hanami.html">initially under the name Lotus</a>. Version 1 was released in April 2017 and version 1.1 was just recently released in October. 

As <a href="http://hanamirb.org/guides/">the introduction to the Hanami guide</a> says, "If you've ever felt you're stretching against the 'Rails way', you'll appreciate Hanami." While this article isn't a comparison of Hanami and Rails, as we build with Hanami you will see the ways in which they differ and be able to decide which approach you prefer.

Let's investigate building a web application with Hanami with a tried and tested Twilio feature, receiving and responding to text messages.

## What you'll need

To build this application you will need a few things:

* A Twilio account (you can <a href="https://www.twilio.com/try-twilio">sign up for a free account</a> if you don’t have one)
* <a href="https://www.twilio.com/console/phone-numbers/incoming">A Twilio phone number</a> that can send and receive SMS messages
* <a href="https://www.ruby-lang.org/en/downloads/">Ruby</a> (I'm using the latest version for this post, 2.4.2, Hanami requires at least 2.3.0)
* <a href="http://bundler.io/">Bundler</a>
* <a href="https://ngrok.com">ngrok</a>, so we can <a href="https://www.twilio.com/blog/2015/09/6-awesome-reasons-to-use-ngrok-when-testing-webhooks.html">expose our development server to Twilio’s webhooks</a>

Once you have those bits we can install Hanami and get started with our application.

## Creating a Hanami application

To create a Hanami app we first need to install the gem. Open up a terminal and enter:

```
gem install hanami
```

Now generate a new Hanami project and install the dependencies:

```
hanami new messages
cd messages
bundle install
```

We have a Hanami app which we can run. Enter:

```
bundle exec hanami server
```

Visit <a href="http://localhost:2300">http://localhost:2300</a> and you will see that you are now running your Hanami application.

<img alt="The default Hanami page visible in a browser." src="https://twilioinc.wpengine.com/wp-content/uploads/2017/11/b8ZuPjZKSE4SZDOK99bj3C2nsej3-kJfTBgMFHFokM2G6ic-iRLcUego6aWcxrISWqsJ3RpzT0bvN3WujdheFqgiOXsdSFv4ZQkofwaoaD3dUv1AqHEqsH8n0oWh9RTW2k8a0w8.png" class="aligncenter">

## Monolith first

Hanami projects are <a href="http://hanamirb.org/guides/1.1/architecture/overview/">described as "monolith first"</a>. Microservices might not be necessary when you first start out building a web application, but that may be something you want to take advantage of later. Hanami is built to accommodate that in its architecture.

Hanami projects consist of two parts:

1. The core, which includes your models, storage, mailers and other objects that implement the business logic. You can find the core in the `lib` folder of your Hanami project
2. A collection of apps that are responsible for exposing the functionality to the outside world. You can find the default "web" app in the `apps` folder

Apps are Hanami's solution for sharing core business logic across different ways of presenting and accessing the data. The default app is for the public website for your project, <a href="http://hanamirb.org/guides/1.1/architecture/overview/#monolith-first">you might create a new app </a>for presenting the same data only to your site's admins.

We'll use a new app for the endpoints we want to expose to Twilio's webhooks as they are a fundamentally different representation to our default web UI. Generate a new app with the following command:

```
bundle exec hanami generate app webhooks
```

You will now find a new directory in the `apps` directory called "webhooks".

### Configuring the app

Now we have a separate app for responding to webhooks and we can configure it differently from the web interface. <a href="https://www.twilio.com/docs/guides/how-to-receive-and-reply-in-ruby#what-is-a-webhook">Twilio webhooks</a> expect <a href="https://www.twilio.com/docs/api/twiml">TwiML</a> in response, so we should always be responding with XML. We can configure our webhooks app to do just that.

Open `apps/webhooks/application.rb` and find the `default_response_format`. Uncomment it and change it from `:html` to `:xml` and save.

```ruby
default_response_format :xml
```

That simple change shows the power of having multiple apps that provide different delivery mechanisms for the core project. The web app still responds with HTML by default and now our webhooks app will default to XML.

### Generating an Action

To receive and respond to an incoming SMS message we will need an action. Hanami provides generators to write the boilerplate code for us, so run the following:

```
bundle exec hanami generate action webhooks sms#create
```

This creates a number of things:

* A route in `apps/webhooks/config/routes.rb`. <a href="http://guides.rubyonrails.org/routing.html#resource-routing-the-rails-default">Like in Rails</a>, Hanami tries to map between HTTP verbs and REST when generating routes, so since we generated a "create" action we now have a `POST` route
* An SMS controller, which is a namespace in which the action classes reside
* A create action, which is a class within the SMS controller that has a `call` method that will be called when a POST request is made to the route
* A view for the create action, which handles rendering the response to the action
* A template for the create action

It's about time to write some code, not just run generators. Let's get started with a test!

## Testing in Hanami

Hanami is very focused on testing, even the <a href="http://hanamirb.org/guides/1.1/getting-started/">getting started guide</a> drives the features you build through tests. In that spirit, let's put a test together for our TwiML endpoint.

Let's build a integration test for now, you'll see why as we continue with our feature.

Hanami includes <a href="http://teamcapybara.github.io/capybara/">Capybara</a> for integration tests on interactive pages, but <a href="http://hanamirb.org/guides/actions/testing/#requests-tests">the documentation recommends using `Rack::Test` to test machine readable endpoints like API responses</a>. Create a folder in `spec/webhooks` called `requests`, then within `requests` create a file called `sms_spec.rb`. Add the following test:

```ruby
require 'spec_helper'

describe "Webhooks SMS response" do
  include Rack::Test::Methods

  def app
    Hanami.app
  end

  it "is successful" do
    post "/webhooks/sms"

    last_response.must_be :ok?
    twiml = Twilio::TwiML::MessagingResponse.new.message(body: 'Hello from Hanami!')
    last_response.body.must_equal twiml.to_s
    last_response.headers['Content-Type'].must_equal 'application/xml; charset=utf-8'
  end
end
```

Before we run this test, you will notice we need the twilio-ruby gem to generate our test XML. Install the gem by adding it to your `Gemfile`:

```ruby
source 'https://rubygems.org'

gem 'rake'
gem 'hanami',           '~> 1.1'
gem 'hanami-model', '~> 1.1'

gem 'sqlite3'

gem 'twilio-ruby'

group :development do
```

and running `bundle install`.

Now, running the test should give us an error.

```
bundle exec rake spec
```

<img alt="A screenshot of the results for running the application tests. 5 runs, 5 assertions, 0 failures, 1 error, 1 skip." src="https://twilioinc.wpengine.com/wp-content/uploads/2017/11/VcXK-szZIm-TbDe3eNf9qMs0TYJwhM-7fZRNnOHDVf2Cjcgb90yvdYVa54aq7Aoy2KhD21fR3W2LVlsoIm1wiTxT3ViLIo3auMLW2KPY0F6uP5Fd6P5jE6xdkHNSEvZAY1SYyns.png" class="aligncenter">

Let's fix that.

## Template driven views

The action generator created `apps/webhooks/templates/sms/create.html.erb`. We already updated our application to return XML, so first rename this file to `create.xml.erb`. We can fill this with <a href="https://www.twilio.com/docs/api/twiml/sms/message">the TwiML we need to respond to an incoming SMS message</a>:

```xml
<?xml version="1.0" encoding="UTF-8"?>
<Response>
  <Message>Hello from Hanami!</Message>
</Response>
```

Run the test again.

<img alt="More test results, this time: 5 runs, 7 assertions, 1 failure, 0 errors, 1 skip." src="https://twilioinc.wpengine.com/wp-content/uploads/2017/11/SK8sTdHuHHFwk_axGQysSinV3FBSBkklJH1thooxIS1OpuPUoLyQt5-wIgrP1Ue8fWK1zzBBZDavbkJXk7Up8VjcVU2Ohtt56g5awfAZJDNAJL_VG8ApnaQpWXn9dQEfc9RIp1Y.png" class="aligncenter">

Hmmm… it should pass, but it is failing due to the line breaks and indentation in our response. We could fix it by removing this unnecessary whitespace from our template, but let's investigate other ways to produce this output instead.

## Bypassing templates from the view

Unlike Rails, Hanami views are objects. This helps separate concerns as the view objects are solely responsible for returning a string that will be rendered as the body of the response. Because of this we can bypass templates entirely, rendering the body straight from the view.

Open `apps/webhooks/views/sms/create.rb` and add the following:

```ruby
module Webhooks::Views::Sms
  class Create
    include Webhooks::View
    
    def render
      twiml = Twilio::TwiML::MessagingResponse.new
      twiml.message body: 'Hello from Hanami!'
      raw twiml.to_s
    end
  end
end
```

By overriding the `render` method we short circuit the template and render TwiML from the view. We use the `raw` method to ensure the XML isn't escaped.

This does feel wrong though. The view's job is to render, not create the objects that we are going to render. That is the job of the action.

Open up `apps/webhooks/controllers/sms/create.rb`, you should find an empty `call` method. This method will be called when the action is invoked. We can generate the TwiML here instead, leaving the view to just render the output.

In the action add the following:

```ruby
module Webhooks::Controllers::Sms
  class Create
    include Webhooks::Action

    expose :twiml

    def call(params)
      @twiml = Twilio::TwiML::MessagingResponse.new
      @twiml.message body: 'Hello from Hanami!'
    end
  end
end
```

This code means that when the action is invoked it will generate the TwiML object and then expose it to the view using the `expose` class method. Now the view only has to worry about rendering that content. In `apps/webhooks/views/sms/create.rb` replace the render method with:

```ruby
    def render
      raw twiml.to_s
    end
```

Run the tests this time and they pass.

<img alt="5 runs, 8 assertions, 0 failures, 0 errors." src="https://twilioinc.wpengine.com/wp-content/uploads/2017/11/t3CLzOtSWOOmSSNbMzC5NxtoK2L0aRt1St31wca6we4OASRfwmCcEndqM5vbyKHq3y0d1D1vbi41awGQm_Q54AjUrG8vYKOzw0dgw7nE4Byk37iE3gLCT4duBA1AgzXRi78OW-8.png" style="width: 602.00px; height: 265.33px; margin-left: 0.00px; margin-top: 0.00px; transform: rotate(0.00rad) translateZ(0px); -webkit-transform: rotate(0.00rad) translateZ(0px);" title="" class='" aligncenter'>

## Bypassing the view from the action

At this stage the view isn't really doing very much, so why not just bypass it too? This can lead to a small performance improvement in the application as we avoid creating unnecessary objects.

To bypass the view you can assign to the action's `body`. Replace the code in `apps/webhooks/controllers/sms/create.rb`with:

```ruby
module Webhooks::Controllers::Sms
  class Create
    include Webhooks::Action

    def call(params)
      @twiml = Twilio::TwiML::MessagingResponse.new
      @twiml.message body: 'Hello from Hanami!'
      self.body = @twiml.to_s
    end
  end
end
```

You can now delete the view, along with its test (`spec/webhooks/views/sms/create_spec.rb`), and the template since we no longer use them. Run the tests again and you'll see them passing. This means we are ready to connect the app to a phone number.

## Connecting to Twilio

We need to expose our application to the internet to respond to an incoming text message with the action we just created. First, make sure you're running the application. If you're not, run:

```
bundle exec hanami server
```

<a href="https://www.twilio.com/blog/2015/09/6-awesome-reasons-to-use-ngrok-when-testing-webhooks.html">I like to use a tool called ngrok</a> to expose the application. Follow the instructions to <a href="https://ngrok.com/download">download and install ngrok</a>. Then run ngrok passing the port number we want to forward traffic to. Hanami runs on port 2300 by default, so run:

```
ngrok http 2300
```

You will see ngrok running and see the URL that is now forwarding to your Hanami application. Grab the URL, you're going to need that in your Twilio console.

<img alt="The ngrok dashboard, you need to copy the URL that it creates for you." src="https://twilioinc.wpengine.com/wp-content/uploads/2017/11/gsBpuLzbpKAuBgXQe8WS9-rOwwLQwdVjhwHGj8ZRaf44R0pYmrkmguEUZd_CGkqSmMgkd7DvPbZT-koo7B8bKYnNxkZZWlfz26gHLXgDTf9wxv8zaEVIbEph9ZFU7OmpzZ2gc2M.png" class="aligncenter">

Open the <a href="https://www.twilio.com/console">Twilio console</a> and head to the <a href="https://www.twilio.com/console/phone-numbers/incoming">numbers dashboard</a>. If you already have a number you want to use for this, then click on it to edit, otherwise, buy yourself a new SMS capable phone number.

Once you have your number it's time to set the webhook URL for incoming messages. Take the ngrok URL you got earlier and add the path to our action, `/webhooks/sms`, to it. Enter this in the field for when a message comes in.

<img alt="Enter the URL in the field in the Messages section marked 'A message comes in'." src="https://twilioinc.wpengine.com/wp-content/uploads/2017/11/NjTruqAK0kRmtbpyacPebj8Q2toEHS3lHeNAt4rdBAXE9AIyGMQD0ZFF6Frhu1w6DCKcmf8JNlDKR1t7urJRd0H3RbAp8RTNGZdAWhCNvKFKpXWzKRfUzXkSZhcFF8F_rD6N3a8.png" class="aligncenter">

Save that and grab your phone. Send a text message to your Twilio number and wait for your message back from your Hanami application.

<img alt="An animation showing a message being sent from a phone and the reply from the application being received." src="https://twilioinc.wpengine.com/wp-content/uploads/2017/11/GSrV5cjQGcPWUiES-xJuxBmU-tp2BBmI5xp_-X63DFoudOSJbaE19l-8jQ9QnJc-RfXK5l-Wri0orwY2Ea-DzVlfWghGJZg5zAwSx5zILGPTrCBnn0bNmupbz5jAACB8-uLC5zs.png" class="aligncenter">

## Welcome to Hanami

We've seen how to set up Hanami to receive and respond to incoming SMS messages. If you want to see the final code <a href="https://github.com/philnash/sms-messages-hanami">check out the application on GitHub</a>. If you want to learn more about Hanami I recommend the <a href="http://hanamirb.org/guides/1.1/getting-started/">Hanami Guides</a>.

Not only have we built a Hanami app that can respond to SMS messages, we've also seen how flexible Hanami is as a framework.

* You can create different apps within one project with different configurations
* There are specific objects for each stage of responding to an incoming request making it easy to separate the concerns of the application
* You can bypass templates and views if you don't need them

This power and flexibility combined makes Hanami a valid competitor to Rails for me. Let me know what you think about Hanami and if you would consider it for your next application. Hit me up on <a href="https://www.twitter.com/philnash">Twitter as @philnash</a>, drop me an email at <a class="c2" href="mailto:philnash@twilio.com">philnash@twilio.com</a> or leave a comment below.

___

_[How to receive and respond to text messages in Ruby with Hanami and Twilio](https://www.twilio.com/blog/2017/11/how-to-receive-and-respond-to-text-messages-in-ruby-with-hanami-and-twilio.html) was originally published on the [Twilio blog](https://www.twilio.com/blog) on November 21, 2017._