Joe Czucha
Joe Czucha

Reputation: 4295

Dynamically specifying a serializer based on a property of a model

I'm trying to dynamically specify a serializer based on a property of a model (within a parent serializer):

ActiveModel::Serializer.setup do |config|
  config.embed = :ids
  config.embed_in_root = true
end

class DocumentSerializer < ActiveModel::Serializer

  attributes :id, :name, :document_layout

  if attributes[:document_layout] === 'portrait'
    has_many :pages, serializer: PortraitPageSerializer
  elsif attributes[:document_layout] === 'landscape'
    has_many :pages, serializer: LandscapePageSerializer
  end

end

but this doesn't seem to work (I guess attributes isn't simply a hash).

Is there another way to access the value? Or am I going about this completely the wrong way?

Upvotes: 1

Views: 1322

Answers (1)

Mark Swardstrom
Mark Swardstrom

Reputation: 18080

Was thinking more about this (it's been a while since I was working on Serializers), would this work?

class DocumentSerializer < ActiveModel::Serializer

  attributes :id, :name
  has_many :portrait_pages, key: pages, serializer: PortraitPageSerializer
  has_many :landscape_pages, key: pages, serializer: LandscapePageSerializer

  def portrait_pages
    pages if object.document_layout === 'portrait'
  end

  def landscape_pages
    pages if object.document_layout === 'landscape'
  end

end

Another option here - subclass your document to have a LandscapeDocument and PortraitDocument. This could be based on type, which lines up with your document_layout field. A thought...

Upvotes: 1

Related Questions