Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add dot params transformer #27

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions lib/remote_record/transformers.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
26 changes: 26 additions & 0 deletions lib/remote_record/transformers/dot_params.rb
Original file line number Diff line number Diff line change
@@ -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
29 changes: 29 additions & 0 deletions spec/transformers_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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