Last active
April 18, 2020 06:58
-
-
Save amolpujari/fd89568abaf492d7d4d62963e0deb278 to your computer and use it in GitHub Desktop.
rails 5 fast_jsonapi oj serializer
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 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