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
4 changes: 4 additions & 0 deletions lib/graphiti/resource/configuration.rb
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,10 @@ def polymorphic=(klasses)
send(:prepend, Polymorphism)
end

def polymorphic?
polymorphic.present?
end

def type=(val)
val = val&.to_sym
if (val = super)
Expand Down
10 changes: 10 additions & 0 deletions lib/graphiti/resource/polymorphism.rb
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ def self.prepended(klass)
end

def serializer_for(model)
return super unless self.class.polymorphic?

if polymorphic_child?
serializer
else
Expand All @@ -17,10 +19,14 @@ def serializer_for(model)
end

def associate_all(*args)
return super unless self.class.polymorphic?

_associate(:associate_all, *args)
end

def associate(*args)
return super unless self.class.polymorphic?

_associate(:associate, *args)
end

Expand All @@ -34,6 +40,8 @@ def _associate(meth, parent, other, association_name, type)

module ClassMethods
def inherited(klass)
return super unless polymorphic?

klass.type = nil
klass.model = klass.infer_model
klass.endpoint = klass.infer_endpoint
Expand All @@ -42,6 +50,8 @@ def inherited(klass)
end

def sideload(name)
return super unless polymorphic?

if (split_on = name.to_s.split(/^on__/)).length > 1
on_type, name = split_on[1].split("--").map(&:to_sym)
end
Expand Down
20 changes: 19 additions & 1 deletion spec/polymorphism_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@
context "when unknown model returned" do
around do |e|
original = PORO::CreditCardResource.polymorphic
PORO::CreditCardResource.polymorphic = []
PORO::CreditCardResource.polymorphic = [PORO::VisaResource]
begin
e.run
ensure
Expand All @@ -69,6 +69,24 @@
}.to raise_error(Graphiti::Errors::PolymorphicResourceChildNotFound)
end
end

context "when no subclasses are configured" do
around do |e|
original = PORO::CreditCardResource.polymorphic
PORO::CreditCardResource.polymorphic = []
begin
e.run
ensure
PORO::CreditCardResource.polymorphic = original
end
end

it "behaves like a non-polymorphic resource" do
expect(PORO::CreditCardResource).not_to be_polymorphic
expect { resource.all.to_a }.not_to raise_error
expect(resource.new.serializer_for(mastercard)).to eq(resource.serializer)
end
end
end

context "via subclass" do
Expand Down
Loading