1
0
Fork 0

Render JSON

This commit is contained in:
Alex Kotov 2023-02-05 06:44:16 +04:00
parent 5afe75ef48
commit ae77d93fe3
Signed by: kotovalexarian
GPG key ID: 553C0EBBEB5D5F08
4 changed files with 18 additions and 15 deletions

View file

@ -1 +1 @@
ruby-3.0.4 ruby-2.7.4

View file

@ -7,3 +7,4 @@ gem 'puma', '~> 6.0'
gem 'connection_pool', '2.2.2' gem 'connection_pool', '2.2.2'
gem 'pg', '1.2.3' gem 'pg', '1.2.3'
gem 'sinatra', '2.0.8.1' gem 'sinatra', '2.0.8.1'
gem 'sinatra-contrib', '2.0.8.1'

View file

@ -1,7 +1,9 @@
GEM GEM
remote: https://rubygems.org/ remote: https://rubygems.org/
specs: specs:
backports (3.23.0)
connection_pool (2.2.2) connection_pool (2.2.2)
multi_json (1.15.0)
mustermann (1.1.2) mustermann (1.1.2)
ruby2_keywords (~> 0.0.1) ruby2_keywords (~> 0.0.1)
nio4r (2.5.8) nio4r (2.5.8)
@ -17,9 +19,17 @@ GEM
rack (~> 2.0) rack (~> 2.0)
rack-protection (= 2.0.8.1) rack-protection (= 2.0.8.1)
tilt (~> 2.0) 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) tilt (2.0.11)
PLATFORMS PLATFORMS
ruby
x86_64-linux x86_64-linux
DEPENDENCIES DEPENDENCIES
@ -27,6 +37,7 @@ DEPENDENCIES
pg (= 1.2.3) pg (= 1.2.3)
puma (~> 6.0) puma (~> 6.0)
sinatra (= 2.0.8.1) sinatra (= 2.0.8.1)
sinatra-contrib (= 2.0.8.1)
BUNDLED WITH BUNDLED WITH
2.4.6 2.4.6

19
main.rb
View file

@ -4,6 +4,7 @@
require 'connection_pool' require 'connection_pool'
require 'pg' require 'pg'
require 'sinatra' require 'sinatra'
require 'sinatra/json'
$DB_POOL = ConnectionPool.new size: 5, timeout: 5 do $DB_POOL = ConnectionPool.new size: 5, timeout: 5 do
PG.connect( PG.connect(
@ -16,18 +17,14 @@ $DB_POOL = ConnectionPool.new size: 5, timeout: 5 do
end end
end end
before do
headers 'X-Frame-Options' => ''
end
get '/examples' do get '/examples' do
$DB_POOL.with do |db_conn| $DB_POOL.with do |db_conn|
ids = ids =
case params[:ids] case params[:ids]
when Array then params[:ids].map { |id| Integer id } when Array then params[:ids]
when String then params[:ids].split(',').map { |id| Integer id } when String then params[:ids].split(',')
else raise 'Invalid param "ids"' else raise 'Invalid param "ids"'
end end.map { |id| Integer id }
examples = db_conn.exec_params( examples = db_conn.exec_params(
( (
@ -54,12 +51,6 @@ get '/examples' do
[PG::TextEncoder::Array.new.encode(ids)], [PG::TextEncoder::Array.new.encode(ids)],
).map { |row| row['values'] } ).map { |row| row['values'] }
<<~HTML json examples
<ul>
#{examples.map do |example|
"<li>#{example[0]} &mdash; #{example[1]}</li>"
end.join}
</ul>
HTML
end end
end end