active_model_serializers/test/fixtures/poro.rb
Guillermo Iguaran 19ac139880 Handle correctly null associations
null belongs_to associations are now serialized as nil instead
of raise an error during serialization.
2014-10-30 09:35:05 -05:00

61 lines
1.0 KiB
Ruby

class Model
def initialize(hash={})
@attributes = hash
end
def read_attribute_for_serialization(name)
if name == :id || name == 'id'
id
else
@attributes[name]
end
end
def id
@attributes[:id] || @attributes['id'] || object_id
end
def method_missing(meth, *args)
if meth.to_s =~ /^(.*)=$/
@attributes[$1.to_sym] = args[0]
elsif @attributes.key?(meth)
@attributes[meth]
else
super
end
end
end
class Profile < Model
end
class ProfileSerializer < ActiveModel::Serializer
attributes :name, :description
urls :posts, :comments
end
Post = Class.new(Model)
Comment = Class.new(Model)
Author = Class.new(Model)
PostSerializer = Class.new(ActiveModel::Serializer) do
attributes :title, :body, :id
has_many :comments
belongs_to :author
url :comments
end
CommentSerializer = Class.new(ActiveModel::Serializer) do
attributes :id, :body
belongs_to :post
end
AuthorSerializer = Class.new(ActiveModel::Serializer) do
attributes :id, :name
has_many :posts, embed: :ids
end