From ae77d93fe38f9438f8b24e706c701616740ddf5d Mon Sep 17 00:00:00 2001 From: Alex Kotov Date: Sun, 5 Feb 2023 06:44:16 +0400 Subject: [PATCH] Render JSON --- .ruby-version | 2 +- Gemfile | 1 + Gemfile.lock | 11 +++++++++++ main.rb | 19 +++++-------------- 4 files changed, 18 insertions(+), 15 deletions(-) diff --git a/.ruby-version b/.ruby-version index 79bc2c7..30c5992 100644 --- a/.ruby-version +++ b/.ruby-version @@ -1 +1 @@ -ruby-3.0.4 +ruby-2.7.4 diff --git a/Gemfile b/Gemfile index 61d3ab2..379c731 100644 --- a/Gemfile +++ b/Gemfile @@ -7,3 +7,4 @@ gem 'puma', '~> 6.0' gem 'connection_pool', '2.2.2' gem 'pg', '1.2.3' gem 'sinatra', '2.0.8.1' +gem 'sinatra-contrib', '2.0.8.1' diff --git a/Gemfile.lock b/Gemfile.lock index b6076cf..6d661fa 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -1,7 +1,9 @@ GEM remote: https://rubygems.org/ specs: + backports (3.23.0) connection_pool (2.2.2) + multi_json (1.15.0) mustermann (1.1.2) ruby2_keywords (~> 0.0.1) nio4r (2.5.8) @@ -17,9 +19,17 @@ GEM rack (~> 2.0) rack-protection (= 2.0.8.1) tilt (~> 2.0) + sinatra-contrib (2.0.8.1) + backports (>= 2.8.2) + multi_json + mustermann (~> 1.0) + rack-protection (= 2.0.8.1) + sinatra (= 2.0.8.1) + tilt (~> 2.0) tilt (2.0.11) PLATFORMS + ruby x86_64-linux DEPENDENCIES @@ -27,6 +37,7 @@ DEPENDENCIES pg (= 1.2.3) puma (~> 6.0) sinatra (= 2.0.8.1) + sinatra-contrib (= 2.0.8.1) BUNDLED WITH 2.4.6 diff --git a/main.rb b/main.rb index 2a30422..38d33af 100755 --- a/main.rb +++ b/main.rb @@ -4,6 +4,7 @@ require 'connection_pool' require 'pg' require 'sinatra' +require 'sinatra/json' $DB_POOL = ConnectionPool.new size: 5, timeout: 5 do PG.connect( @@ -16,18 +17,14 @@ $DB_POOL = ConnectionPool.new size: 5, timeout: 5 do end end -before do - headers 'X-Frame-Options' => '' -end - get '/examples' do $DB_POOL.with do |db_conn| ids = case params[:ids] - when Array then params[:ids].map { |id| Integer id } - when String then params[:ids].split(',').map { |id| Integer id } + when Array then params[:ids] + when String then params[:ids].split(',') else raise 'Invalid param "ids"' - end + end.map { |id| Integer id } examples = db_conn.exec_params( ( @@ -54,12 +51,6 @@ get '/examples' do [PG::TextEncoder::Array.new.encode(ids)], ).map { |row| row['values'] } - <<~HTML - - HTML + json examples end end