mirror of
https://github.com/usetrmnl/trmnl-api.git
synced 2026-04-29 13:35:13 -07:00
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:
@@ -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
|
||||
@@ -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
|
||||
Reference in New Issue
Block a user