When it comes to structure in Sinatra apps, you can have regular — sometimes referred to as “classical” — apps, or “modular” ones.
In a classical Sinatra app, all your code lives in one file. You’ll almost always find that you can only run one Sinatra app per Ruby process if you choose the regular app structure.
The example below shows a simple classical Sinatra app.
ruby
# main.rb require 'sinatra' require 'json' get '/' do # here we specify the content type to respond with content_type :json { item: 'Red Dead Redemption 2', price: 19.79, status: 'Available' }.to_json end
This one file contains everything needed for this simplified app to run. Run it with ruby main.rb
, which should spin up an instance of the Thin web server (the default web server that comes with Sinatra). Visit localhost:4567
and you’ll see the JSON response.
As you can see, it is relatively easy to extend this simple example into a fairly-complex API app with everything contained in one file (the most prominent feature of the classical structure).
Now let’s turn our attention to modular apps.
The code below shows a basic modular Sinatra app. At first glance, it looks pretty similar to the classic app we’ve already looked at — apart from a rather simple distinction. In modular apps, we subclass Sinatra::Base
, and each “app” is defined within this subclassed scope.
ruby
# main.rb require 'sinatra/base' require 'json' require_relative 'lib/fetch_game_data' # main module/class defined here class GameStoreApp < Sinatra::Base get '/' do content_type :json { item: 'Red Dead Redemption 2', price: 19.79, status: 'Available' }.to_json end not_found do content_type :json { status: 404, message: "Nothing Found!" }.to_json end end
Have a look at the Sinatra documentation in case you need more information on this.
Let’s now continue with our app build.
Leave a Reply