Skip to content

Instantly share code, notes, and snippets.

@mreigen
Created July 1, 2017 22:11
Show Gist options
  • Save mreigen/a009652d59fb84f3015320040727c116 to your computer and use it in GitHub Desktop.
Save mreigen/a009652d59fb84f3015320040727c116 to your computer and use it in GitHub Desktop.
Rails Serializer: Custom attributes based on passed in options
class AnimalSerializer < ActiveModel::Serializer
def initialize(object, options)
if options[:type] == 'giraffe'
self.class.attributes :skin_pattern, :leg_length
else
self.class.attributes :number_of_legs
end
super(object, options)
end
...
end
AnimalSerializer.new(result, root: false, type: 'giraffe').as_json
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment