Skip to content
Merged
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
13 changes: 13 additions & 0 deletions lib/intercom/traits/api_resource.rb
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,10 @@ def initialize(attributes = {})
from_hash(attributes)
end

def ==(other)
self.class == other.class && to_json == other.to_json
end

def from_response(response)
from_hash(response)
reset_changed_fields!
Expand All @@ -37,6 +41,15 @@ def to_hash
end
end

def to_json(*args)
instance_variables_excluding_dirty_tracking_field.each_with_object({}) do |variable, hash|
next if variable == :@client

value = instance_variable_get(variable)
hash[variable.to_s.delete('@')] = value.respond_to?(:to_json) ? value.to_json(*args) : value
end
end

def to_submittable_hash
submittable_hash = {}
to_hash.each do |attribute, value|
Expand Down
26 changes: 24 additions & 2 deletions spec/unit/intercom/traits/api_resource_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@
it 'an initialized ApiResource is equal to one generated from a response' do
class ConcreteApiResource; include Intercom::Traits::ApiResource; end
initialized_api_resource = ConcreteApiResource.new(object_json)
except(object_json, 'type', 'nested_fields').keys.each do |attribute|
except(object_json, 'type').keys.each do |attribute|
assert_equal initialized_api_resource.send(attribute), api_resource.send(attribute)
end
end
Expand All @@ -122,11 +122,33 @@ class ConcreteApiResource; include Intercom::Traits::ApiResource; end

api_resource.from_hash(object_hash)
initialized_api_resource = ConcreteApiResource.new(object_hash)
except(object_json, 'type', 'nested_fields').keys.each do |attribute|
except(object_json, 'type').keys.each do |attribute|
assert_equal initialized_api_resource.send(attribute), api_resource.send(attribute)
end
end

describe 'correctly equates two resources' do
class DummyResource; include Intercom::Traits::ApiResource; end

specify 'if each resource has the same class and same value' do
api_resource1 = DummyResource.new(object_json)
api_resource2 = DummyResource.new(object_json)
assert_equal (api_resource1 == api_resource2), true
end

specify 'if each resource has the same class and different value' do
object2_json = object_json.merge('id' => 'bbbbbb')
api_resource1 = DummyResource.new(object_json)
api_resource2 = DummyResource.new(object2_json)
assert_equal (api_resource1 == api_resource2), false
end

specify 'if each resource has a different class' do
dummy_resource = DummyResource.new(object_json)
assert_equal (dummy_resource == api_resource), false
end
end

it 'correctly generates submittable hash when no updates' do
assert_equal api_resource.to_submittable_hash, {}
end
Expand Down