Skip to content

Filtering keys at serializer level #16

Description

@oyeanuj

Hi @yosiat, another question about an AMS as I analyze my code to estimate effort to migrate:

I use the following two patterns quite a bit to ensure the user gets data consistent with their level of authorization:

#1 Pattern: Utilizing the fact that AMS calls `filter` for each serializer

class PostSerializer < ActiveModel::Serializer
     # ..attributes comes here

	def filter(keys)
		if scope && scope.is_admin?
			keys
			
		else
			keys - [:draft, :created_at, :notes]

		end
	end
end
#2 Pattern: Using AMS `initialize` and `attributes` method

class PostSerializer < ActiveModel::Serializer

  #.. basic attributes come here

  def initialize(object, options = {})
		@owner = scope && (object.id == scope.id) ? true : false
		@logged_in = scope
		super(object, options)
	end

	def attributes(*args)
		return super if @owner
		if @logged_in
			attributes_to_remove = [
				:preview,
			]

		else
			attributes_to_remove = [
				:is_published
			]

		end
		filtered = super.except(*attributes_to_remove)
		filtered
	end
end

How can I achieve the same with Panko so that whenever Post Serializer is called, it renders appropriately?

Thank you!

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions