ruby-on-railsapiactive-model-serializersruby-grapegrape-api

Versioning Grape active_model_serializer


I'm trying to make a V2 api for my rails app with grape and grape_active_model_serializer. But I can't figure how to make a serializer for each version of my api.

Here is what my api look like

app/api/api.rb :

require 'grape-swagger'
class API < Grape::API
  prefix 'api'
  format :json
  formatter :json, Grape::Formatter::ActiveModelSerializers
  use ::WineBouncer::OAuth2

  <... some code here ...>

  mount V1::APIV1
  add_swagger_documentation api_version: 'v1',
                            hide_documentation_path: false,
                            hide_format: true
  mount V2::APIV2
  add_swagger_documentation api_version: 'v2',
                            hide_documentation_path: false,
                            hide_format: true
end

app/api/v1/apiv1.rb

module V1
  class APIV1 < Grape::API
    version 'v1', using: :path

    mount V1::UsersController
  end
end

app/api/v2/apiv2.rb

module V2
  class APIV2 < Grape::API
    version 'v2', using: :path

    mount V2::UsersController
  end
end

app/serializers/v1

class UserSerializer < ActiveModel::Serializer
  include Serializer

  attributes  :email,
              :username,
              :first_name,
              :last_name

app/serializers/v2

class UserSerializer < ActiveModel::Serializer
  include Serializer

  attributes  :email,
              :username,
              :first_name,
              :last_name,
              :phone_number,
              :adress

and I added to my config/application.rb

config.autoload_paths += Dir[Rails.root.join('app', 'serializers', '**/')]

For now, V1 and V2 users controller are returning the same json whithout phone number and adress, how can I tell to my v2 api to use the v2 serializer ?

I'm using grape, grape-active_model_serializers, grape-swagger and grape-swagger-rails


Solution

  • Actually it was quite simple, after I had tried sorcery and shamanism rails give me the hint, If you divide your serializers into module that works fine some so now I have

     module V1
       class UserSerializer < ActiveModel::Serializer
        include Serializer
    
        attributes  :email,
              :username,
              :first_name,
              :last_name
    

    and

     module V2
       class UserSerializer < ActiveModel::Serializer
        include Serializer
    
        attributes  :email,
              :username,
              :first_name,
              :last_name,
              :phone_number,
              :adress
    

    I put the answer because I saw a lot of questionning about the versionning of serializers sorry for the bad english but I don't have potatoes -)