Skip to content

Commit

Permalink
fix(copyable): do not mutate input params
Browse files Browse the repository at this point in the history
  • Loading branch information
marian13 committed Feb 1, 2023
1 parent 0d9ba16 commit 0809592
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 2 deletions.
8 changes: 6 additions & 2 deletions lib/convenient_service/support/copyable.rb
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,12 @@ module Copyable
# NOTE: This method is NOT likely to be ever changed, that is why inline logic is preferred over command classes in this particular case.
#
def copy(overrides: {})
overrides[:args] ||= {}
overrides[:kwargs] ||= {}
defaults = {args: {}, kwargs: {}}

##
# IMPORTANT: Do not mutate `overrides`.
#
overrides = defaults.merge(overrides)

##
# TODO: Refactor runtime `respond_to?`. Investigate before refactoring.
Expand Down
26 changes: 26 additions & 0 deletions spec/lib/convenient_service/support/copyable_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,14 @@ def to_block
expect(instance).to have_received(:to_block)
end

context "when `overrides[:args]` is NOT passed" do
let(:overrides) { {} }

it "defaults to empty hash`" do
expect(instance.copy(overrides: overrides).args).to eq(constructor_params[:args])
end
end

context "when `overrides[:args]` is passed" do
context "when `overrides[:args]` is array" do
let(:overrides) { {args: [:baz, :qux]} }
Expand All @@ -109,6 +117,14 @@ def to_block
end
end

context "when `overrides[:kwargs]` is NOT passed" do
let(:overrides) { {} }

it "defaults to empty hash`" do
expect(instance.copy(overrides: overrides).kwargs).to eq(constructor_params[:kwargs])
end
end

context "when `overrides[:kwargs]` is passed" do
let(:overrides) { {kwargs: {foo: 3, bar: 4}} }

Expand All @@ -125,6 +141,16 @@ def to_block
end
end

context "when `overrides` is passed" do
let(:overrides) { {block: proc { :bar }} }

it "does NOT mutate `overrides`" do
overrides.freeze

expect { instance.copy(overrides: overrides) }.not_to raise_error(FrozenError)
end
end

context "when `to_args` is NOT implemented" do
let(:klass) do
Class.new(base_class) do
Expand Down

0 comments on commit 0809592

Please sign in to comment.