Created
July 1, 2017 22:11
-
-
Save mreigen/a009652d59fb84f3015320040727c116 to your computer and use it in GitHub Desktop.
Rails Serializer: Custom attributes based on passed in options
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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