# Simple Sinatra app that acts as a webhook for an api.ai chatbot

I'm in the process of learning Ruby which I never used. I've built quite a few web applications in different languages, but this is my first time using Ruby. Things work, I enjoy writing Ruby, but I feel I might be missing some of its idioms.

This is a simple Sinatra app that acts as a webhook for an api.ai chatbot. The correctness of the code is probably irrelevant, I'd be interested in finding out possibilities of making the code more "Ruby like".

This is just the code for the webhook, I hope (?) the imported methods and classes are self-explanatory.

# frozen_string_literal: true
require 'json'
require 'sinatra'
require 'sinatra/json'
require './lib/helpers'
require './lib/database'
require './lib/config'

db_client = Database::Client.new
wakeup_response = Config::WakeupResponse.new

post '/:bot/webhook' do |bot|
protected!

session_id = params.fetch('sessionId', nil)
if session_id.nil?
return [400, 'No sessionId present in payload.']
end

user = db_client.find_one(bot, session_id)
speech = infer_speech(params)

if user && (currently_active?(params) || reset_intent?(params))
db_client.update_one(
bot,
session_id,
lastContext: params.fetch('result', {}).fetch('contexts', [])
)
elsif user
speech = wakeup_response.get(bot)
else
db_client.insert_one(bot, session_id)
end

user = db_client.find_one(bot, params['sessionId'])

json(
speech: speech,
displayText: speech,
contextOut: user.fetch('lastContext', []),
source: Config.source_name
)
end

post '*' do