Create a context class
This commit is contained in:
parent
8df00a7846
commit
8096d98904
69
main.rb
69
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<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
|
||||
|
|
Loading…
Reference in New Issue