I am encountering errors when passing a SimpleDelegator instance to a Serializer. It seems that the serializer only respects the instance held by __getobj__ and does not forward any methods that are handled in the delegate. This is a bit dense so I put together an example.
require 'delegate'
class A
include ActiveModel::Model
include ActiveModel::Serialization
attr_accessor :name
end
class B
include ActiveModel::Model
include ActiveModel::Serialization
attr_accessor :desc
end
class ABDelegate < SimpleDelegator
attr_reader :b
def initialize a, b
@b = b
super a
end
def desc
b.desc
end
end
class ABSerializer < ActiveModel::Serializer
attributes :name, :desc
end
a = A.new(name: 'Name for A')
b = B.new(desc: 'Desc for B')
delegate = ABDelegate.new(a,b)
serializer = ABSerializer.new(delegate)
puts delegate.name == "Name for A"
=> true
puts delegate.desc == "Desc for B"
=> true
puts serializer.to_json
NoMethodError: undefined method `desc' for #<A:0x007ff5439614d8 @name="Name for A">
(eval):4:in `_fast_attributes'
My expectation would be that the serializer would use the ABDelegate instance but from the error that does not seem to be the case.
@twoism - were you able to find a solution this? I just encountered the same issue.
@twoism nm, I was able to solve it in my case by adding 'include ActiveModel::SerializerSupport' to my class.
Any solution to this?
Running into this problem too. Tried overriding attributes hash, as_json and to_json but it doesn't serialize using any of these values.
I didn't see this getting any traction for a while so I closed it. My solution was a bit heavy handed but it works for me. I wrote a serializer minus all the eval magic that I believe is causing the issue. You're welcome to use it as well.
Hi @twoism what is the version of AMS that you used? :)
I opened the issue in February. I remember trying a couple versions and then giving up. Seeing as others are experiencing this still, I would imagine that this is still an issue.
@joaomdmoura This bit me at work today, too. It fails for me on both master 0.10.0rc1 and the Rubygems latest version, 0.9.3
I created a blank Rails app with a reproduction and a test for you.
@xionon thank you so much! It'll definitely help! I'm having a hard time pushing every PR forward but I'll try to give it some attention asap :smile:
per @rounders's comment, including ActiveModel::SerializerSupport to a delegator fixes this.
ActiveModel::SerializerSupport seems to be no longer available. Is there a more up to date solution for this?
@craigweston Please open a new issue. I don't know what you're trying to do or what version or on or what you've tried. From your comment 'seems to be no longer available' it's unclear what docs you've looked at.
Most helpful comment
@twoism nm, I was able to solve it in my case by adding 'include ActiveModel::SerializerSupport' to my class.