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 'pg', '1.2.3'
gem 'sinatra', '2.0.8.1'
gem 'sinatra-contrib', '2.0.8.1'

View file

@ -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

19
main.rb
View file

@ -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
<ul>
#{examples.map do |example|
"<li>#{example[0]} &mdash; #{example[1]}</li>"
end.join}
</ul>
HTML
json examples
end
end