Added locale reducer

Necessary to provide a reusable function to process locales by dealing with the unnecessary duplication of locale key prefixes in the API responses. This will soon be used by the models.

Milestone: minor
This commit is contained in:
Brooke Kuhlmann
2026-01-15 09:16:22 -07:00
parent 35352a579c
commit 8afdadbe57
2 changed files with 54 additions and 0 deletions
+14
View File
@@ -0,0 +1,14 @@
# frozen_string_literal: true
module TRMNL
module API
LocaleReducer = lambda do |attributes, prefix: "description-"|
attributes.each.with_object({}) do |(key, value), all|
next unless key.start_with? prefix
attributes.delete key
all[key.to_s.delete_prefix(prefix)] = value
end
end
end
end
+40
View File
@@ -0,0 +1,40 @@
# frozen_string_literal: true
require "spec_helper"
RSpec.describe TRMNL::API::LocaleReducer do
subject(:reducer) { described_class }
describe "#call" do
let :attributes do
{
name: "test",
"description-de": "german",
"description-fr": "french",
"description-en-GB": "united_kingdom"
}
end
it "answers locales hash" do
expect(reducer.call(attributes)).to eq(
"de" => "german",
"fr" => "french",
"en-GB" => "united_kingdom"
)
end
it "answers locales hash using custom prefix" do
attributes = {test_de: "german", test_fr: "french"}
expect(reducer.call(attributes, prefix: "test_")).to eq("de" => "german", "fr" => "french")
end
it "answers empty hash when there are no locales" do
expect(reducer.call({one: 1, two: 2})).to eq({})
end
it "mutates input when locales exist" do
original = attributes.dup
expect(reducer.call(attributes)).not_to eq(original)
end
end
end