Micro Services with Sinatra -Part 1
Why to choose Sinatra?

If you are very good in ruby than other language like nodejs or GO. You can easily find a ruby developer and so this is maintainable as compare to other language like elixir, GO It doesn’t come with heavy package like rails and so its perfect choice for micro service. You can add activerecord-sinatra gem and can reuse code if you have existing rails app. Performance over other ruby framework is much better. Sinatra is 3 times faster than Rails API 5 and 7 times faster than Rails 5.

1. Create a new app with Bundler

Create a folder with your project name and add Gemfile .

source 'https://rubygems.org'

git_source(:github) { |repo| "https://github.com/#{repo}.git" }



ruby '2.4.2'



gem 'sinatra', require: 'sinatra'

gem "puma" # to start our server

Create config.ru so that it load bundler before it loads Sinatra app.

require 'rubygems'

require 'bundler'



Bundler.require



require './microservice_with_sinatra_app'

run MicroserviceWithSinatraApp

Now add a new file described in config.r u` i.e. microservice_with_sinatra_app.rb

require_relative 'env'



class MicroserviceWithSinatraApp < Sinatra::Base



get '/' do

'hello world'

end



end

Yes we are missing environments! :). Add a file `env.rb`

require 'bundler/setup'



APP_ENV = ENV["RACK_ENV"] || "development"



Bundler.require :default, APP_ENV.to_sym

start server with following command

bundle exec rackup

Open http://localhost:9292/ and see you hello world app.

2. Configuration with PostgreSQL

This step is totally optional. If you need to do some database storage you may need this step.

Add following gems ..

gem "pg" # for Postgres

gem "rake" # so we can run Rake tasks

gem "sinatra-activerecord", require: 'sinatra/activerecord' # for Active Record models

Modify config.ru as follow:

...

Bundler.require

require 'sinatra/activerecord'

require 'sinatra/activerecord/rake'

...

Create config/database.yml

development:

adapter: postgresql

encoding: unicode

database: database_name

pool: 2

username: your_username

password: your_password



production:

adapter: postgresql

encoding: unicode

pool: 5

host: <%= ENV['DATABASE_HOST'] %>

database: <%= ENV['DATABASE_NAME'] %>

username: <%= ENV['DATABASE_USER'] %>

password: <%= ENV['DATABASE_PASSWORD'] %>

Generate a new migration.

rake db:create_migration NAME=create_table_name

and edit your migration according to your need just like rails migration.

Now you can add desired models and can work just like small rails app. Next will be integrating RabbitMQ and other stuff required to create a micro service. KEEP READING …
['Surat Pyari']
['Postgresql', 'Ruby', 'Microservices', 'Ruby on Rails', 'Sinatra']