From 8096d98904fa0fd11a5581615d6c296a354f799c Mon Sep 17 00:00:00 2001 From: Alex Kotov Date: Sat, 18 Feb 2023 13:44:02 +0400 Subject: [PATCH] Create a context class --- main.rb | 69 +++++++++++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 62 insertions(+), 7 deletions(-) diff --git a/main.rb b/main.rb index 178c887..f745092 100755 --- a/main.rb +++ b/main.rb @@ -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] + # + 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