Here’s an example of how you can build a simple Sinatra server to serve as a chat API in Ruby:
First, you’ll need to install Sinatra and any other dependencies you might need. You can do this by adding the following lines to your Gemfile
and running bundle install
:
gem 'sinatra'
gem 'sequel' # or another database library if you prefer
Then, you can create a new file for your Sinatra server, let’s call it server.rb
. In this file, you’ll first require the necessary libraries and set up your database connection:
require 'sinatra'
require 'sequel' # or whichever database library you're using
DB = Sequel.connect('postgres://localhost/my_database') # replace with your own database connection details
# You might also want to set up your database tables here, if you don't have them already
DB.create_table? :messages do
primary_key :id
String :sender
String :recipient
String :text
Time :timestamp
end
Next, you can define your API routes and their corresponding behavior. For example, you might want to define a route to retrieve all messages in the chat history:
get '/messages' do
messages = DB[:messages].order(:timestamp).all
content_type :json
{ messages: messages }.to_json
end
You can also define routes to create new messages or delete existing ones:
post '/messages' do
data = JSON.parse(request.body.read)
sender = data['sender']
recipient = data['recipient']
text = data['text']
timestamp = Time.now
message_id = DB[:messages].insert(sender: sender, recipient: recipient, text: text, timestamp: timestamp)
content_type :json
{ message_id: message_id }.to_json
end
delete '/messages/:id' do
message_id = params[:id]
DB[:messages].where(id: message_id).delete
status 200
end
Finally, you can start your Sinatra server by running ruby server.rb
. Your chat API will be available at http://localhost:4567
, or whichever port you specify in your code.