diff --git a/lib/remote_record/transformers.rb b/lib/remote_record/transformers.rb index 3e8181b..78c2a50 100644 --- a/lib/remote_record/transformers.rb +++ b/lib/remote_record/transformers.rb @@ -2,6 +2,7 @@ require 'remote_record/transformers/base' require 'remote_record/transformers/snake_case' +require 'remote_record/transformers/dot_params' module RemoteRecord # Classes responsible for transforming the hash of data returned by API calls. diff --git a/lib/remote_record/transformers/dot_params.rb b/lib/remote_record/transformers/dot_params.rb new file mode 100644 index 0000000..d703967 --- /dev/null +++ b/lib/remote_record/transformers/dot_params.rb @@ -0,0 +1,26 @@ +# frozen_string_literal: true + +module RemoteRecord + module Transformers + # Converts keys to dot params. + class DotParams < RemoteRecord::Transformers::Base + def transform + convert_hash_keys(@data).map { |k, v| "#{CGI.escape(k.to_s)}:#{CGI.escape(v.to_s)}" }.join(';') + end + + private + + def convert_hash_keys(data) + data.each_with_object({}) do |(k, v), h| + if v.is_a? Hash + convert_hash_keys(v).map do |h_k, h_v| + h["#{k}.#{h_k}".to_sym] = h_v + end + else + h[k] = v + end + end + end + end + end +end diff --git a/spec/transformers_spec.rb b/spec/transformers_spec.rb index 67e31fc..0689bcc 100644 --- a/spec/transformers_spec.rb +++ b/spec/transformers_spec.rb @@ -32,4 +32,33 @@ it { is_expected.to eq(1) } end end + + describe described_class::DotParams do + let(:transformer) { described_class.new(data, direction) } + subject(:result) { transformer.transform } + + context 'when the direction is not valid' do + let(:direction) { :left } + let(:data) { { userId: 1 } } + + it 'is expected to raise an error' do + expect { transformer }.to raise_error ArgumentError + end + end + + context 'when the direction is up' do + let(:direction) { :up } + let(:data) { { customer: { user_id: 1 }, state: :completed } } + + it { is_expected.to eq('customer.user_id:1;state:completed') } + end + + xcontext 'when the direction is down' do + let(:direction) { :down } + let(:expected_attribute_name) { :userId } + let(:data) { 'customer.user_id:1;state:completed' } + + it { is_expected.to eq({ customer: { user_id: 1 }, state: :completed }) } + end + end end