Feature to define default-unrendered attributes to ActiveModel::Serializers

18 views
Skip to first unread message

Martin Kraft

unread,
Apr 8, 2014, 7:08:42 AM4/8/14
to rails-a...@googlegroups.com
Sometime you want to define attributes for JSON serialization that are only rendered when explicitly mentioned. For example, say there's a User serializer:

class UserSerializer < ActiveModel::Serializer
  attributes :id, :hair_color, :home_address
end

You know in advance that you'll rarely render :home_address, but you don't want to remember to put except: [:home_address] or only: [:id, :hair_color] every time you use the serializer. Rather in a few places you want to explicitly expose :home_address.

One solution would be to define a separate list of attributes that are by default unrendered during serialization:

class UserSerializer < ActiveModel::Serializer
  attributes :id, :hair_color
  hidden_attributes :home_address
end

By default :home_address will not be displayed, but if you want to display it you can do so with the :expose option like so:

UserSerializer.new(user, expose: [:home_address])

I have created a pull request that implements this feature. I'm not sure about the naming of hidden_attributes and :expose, but the basic idea is here: https://github.com/rails-api/active_model_serializers/pull/537
Reply all
Reply to author
Forward
0 new messages