1
0
Fork 0

Create a context class

This commit is contained in:
Alex Kotov 2023-02-18 13:44:02 +04:00
parent 8df00a7846
commit 8096d98904
Signed by: kotovalexarian
GPG Key ID: 553C0EBBEB5D5F08
1 changed files with 62 additions and 7 deletions

69
main.rb
View File

@ -22,10 +22,58 @@ before do
end
get '/words/:id' do
$DB_POOL.with do |db_conn|
Context.call db_pool: $DB_POOL, user_lang_id: nil do |context|
word_id = Integer params[:id]
part_of_speech_name = db_conn.exec_params(
json({
part_of_speech: context.part_of_speech_name(word_id),
examples: context.examples(word_id),
})
end
end
class Context
private_class_method :new
def self.call(db_pool:, **kwargs, &block)
new(**kwargs).send :call, db_pool: db_pool, &block
end
def initialize(user_lang_id:)
self.user_lang_id = user_lang_id
end
private
attr_reader :user_lang_id
def call(db_pool:)
db_pool.with do |db_conn|
@db_conn = db_conn
result = yield self
@db_conn = nil
result
end
end
def user_lang_id=(user_lang_id)
return @user_lang_id = nil if user_lang_id.nil?
user_lang_id = Integer user_lang_id
raise unless user_lang_id.positive?
@user_lang_id = user_lang_id
end
public
##
# @return [String, nil]
#
def part_of_speech_name(word_id)
word_id = Integer word_id
column = @db_conn.exec_params(
(
<<~SQL
SELECT parts.english_name
@ -39,7 +87,17 @@ get '/words/:id' do
[word_id],
).values.first&.first
examples = db_conn.exec_params(
str = String(column).strip.freeze
str unless str.empty?
end
##
# @return [Array<Array(String, String)>]
#
def examples(word_id)
word_id = Integer word_id
result = @db_conn.exec_params(
(
<<~SQL
SELECT
@ -75,9 +133,6 @@ get '/words/:id' do
[word_id],
).map { |row| row['values'] }
json({
part_of_speech: part_of_speech_name,
examples: examples,
})
result.map { |pair| pair.map(&:freeze).freeze }.freeze
end
end