Skip to content

Commit

Permalink
fix: Avoid wrapping empty hash resource values in DeepHashAccessor (#190
Browse files Browse the repository at this point in the history
)
  • Loading branch information
andrii-balitskyi authored Dec 16, 2024
1 parent 63f604a commit 05573f9
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 9 deletions.
26 changes: 17 additions & 9 deletions lib/seam/base_resource.rb
Original file line number Diff line number Diff line change
Expand Up @@ -11,19 +11,12 @@ class BaseResource
def initialize(data, client = nil)
@data = data
@client = client

@data.each do |key, value|
value = Seam::DeepHashAccessor.new(value) if value.is_a?(Hash)
instance_variable_set(:"@#{key}", value)
end
process_data_attributes(@data)
end

def update_from_response(data)
@data = data
@data.each do |key, value|
value = Seam::DeepHashAccessor.new(value) if value.is_a?(Hash)
instance_variable_set(:"@#{key}", value)
end
process_data_attributes(@data)
end

def self.load_from_response(data, client = nil)
Expand Down Expand Up @@ -60,6 +53,21 @@ def self.date_accessor(*attrs)
def parse_datetime(value)
Time.parse(value)
end

def process_data_attributes(data)
data.each do |key, value|
value = process_hash_value(value)
instance_variable_set(:"@#{key}", value)
end
end

def process_hash_value(value)
if value.is_a?(Hash) && !value.empty?
Seam::DeepHashAccessor.new(value)
else
value
end
end
end
end
end
23 changes: 23 additions & 0 deletions spec/resources/deep_hash_accessor_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# frozen_string_literal: true

RSpec.describe Seam::Resources::BaseResource do
describe "hash handling" do
let(:client) { Seam.new(api_key: "seam_some_api_key") }

it "does not wrap empty hashes in DeepHashAccessor" do
data = {
device_id: "123",
empty_hash: {},
non_empty_hash: {key: "value"}
}

resource = described_class.new(data, client)

expect(resource.instance_variable_get(:@empty_hash)).to eq({})
expect(resource.instance_variable_get(:@empty_hash)).to be_a(Hash)
expect(resource.instance_variable_get(:@empty_hash)).not_to be_a(Seam::DeepHashAccessor)

expect(resource.instance_variable_get(:@non_empty_hash)).to be_a(Seam::DeepHashAccessor)
end
end
end

0 comments on commit 05573f9

Please sign in to comment.