diff --git a/lib/trmnl/api/locale_reducer.rb b/lib/trmnl/api/locale_reducer.rb new file mode 100644 index 0000000..2db2868 --- /dev/null +++ b/lib/trmnl/api/locale_reducer.rb @@ -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 diff --git a/spec/lib/trmnl/api/locale_reducer_spec.rb b/spec/lib/trmnl/api/locale_reducer_spec.rb new file mode 100644 index 0000000..01411e0 --- /dev/null +++ b/spec/lib/trmnl/api/locale_reducer_spec.rb @@ -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