stas / jsonapi.rb

Lightweight, simple and maintained JSON:API support for your next Ruby HTTP API.
MIT License
261 stars 57 forks source link

Option to specify the serializer explicitly #89

Closed yankovskiid closed 1 year ago

yankovskiid commented 1 year ago

Expected Behavior

Is it possible to make it possible to specify the serializer explicitly. Gem has a method jsonapi_serializer_class, but there are actually cases where I need a different serializer, so it could be possible to specify one, as is done in rails:

def index
  render jsonapi: foo, each_serializer: FooSerializer
end

def show
  render jsonapi: foo
end

def jsonapi_serializer_class
  BarSerializer
end  

Actual Behavior

def index
  render json: foo, each_serializer: FooSerializer
end

def show
  render jsonapi: foo
end

def jsonapi_serializer_class
  BarSerializer
end

Steps to Reproduce the Problem

N/A

Specifications

stas commented 1 year ago

@yankovskiid did you consider using the action_name and params[:action] ?

I'm reluctant to consider this change since REST-ful APIs usually operate on a single resource, so your example sounds more like an exception rather than a common pattern. Happy to hear your use-case if you want to share more.

Faq commented 5 months ago

Did this in controller:

def jsonapi_serializer_class(resource, is_collection)
    if resource.name.demodulize.snakecase == 'name_you_looking'
      Portal::Members::CollectionSerializer
    else
      JSONAPI::Rails.serializer_class(resource, is_collection)
    end
end