Skip to content

Instantly share code, notes, and snippets.

@amolpujari
Last active April 18, 2020 06:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amolpujari/fd89568abaf492d7d4d62963e0deb278 to your computer and use it in GitHub Desktop.
Save amolpujari/fd89568abaf492d7d4d62963e0deb278 to your computer and use it in GitHub Desktop.
rails 5 fast_jsonapi oj serializer
class ApplicationSerializer
include FastJsonapi::ObjectSerializer
#cache_options enabled: true, cache_length: 1.hour
def to_h
data = serializable_hash
if data[:data].is_a? Hash
data[:data][:attributes]
elsif data[:data].is_a? Array
data[:data].map{ |x| x[:attributes] }
elsif data[:data] == nil
nil
else
data
end
end
class << self
def has_one resource, options={}
serializer = options[:serializer] || "#{resource.to_s.classify}Serializer".constantize
attribute resource do |object|
serializer.new(object.try(resource)).to_h
end
end
def has_many resources, options={}
serializer = options[:serializer] || "#{resources.to_s.classify}Serializer".constantize
attribute resources do |object|
serializer.new(object.try(resources)).to_h
end
end
end
attribute :errors do |object|
object.errors.full_messages
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment