1
0
Fork 0

Specify a locale

This commit is contained in:
Alex Kotov 2023-03-26 05:47:51 +04:00
parent 2ef60bc035
commit 51bf603036
Signed by: kotovalexarian
GPG Key ID: 553C0EBBEB5D5F08
1 changed files with 23 additions and 13 deletions

36
main.rb
View File

@ -22,7 +22,7 @@ before do
end
get '/words/:id' do
Context.call db_pool: $DB_POOL, user_lang_id: 2 do |context|
Context.call db_pool: $DB_POOL, locale: params[:locale] do |context|
word_id = Integer params[:id]
word_info = context.word_info(word_id)
@ -45,30 +45,40 @@ class Context
new(**kwargs).send :call, db_pool: db_pool, &block
end
def initialize(user_lang_id:)
self.user_lang_id = user_lang_id
def initialize(locale:)
self.locale = locale
end
private
attr_reader :user_lang_id
attr_reader :locale, :locale_id
def call(db_pool:)
db_pool.with do |db_conn|
@locale_id = db_conn.exec_params(
(
<<~SQL
SELECT id
FROM languages
WHERE code = $1
ORDER BY
(CASE WHEN code != 'en' THEN 1 ELSE 2 END) ASC
LIMIT 1
SQL
),
[locale],
).values.first&.first
@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
def locale=(locale)
@locale = String(locale).strip.freeze
end
public
@ -121,7 +131,7 @@ public
LIMIT 1
SQL
),
[word_id, user_lang_id],
[word_id, locale_id],
).values.first&.first
str = String(column).strip.freeze
@ -149,7 +159,7 @@ public
ORDER BY translations.index ASC
SQL
),
[word_id, user_lang_id],
[word_id, locale_id],
).to_a
values.map.with_index do |row, index|