【问题标题】:Versioning Grape active_model_serializer版本控制葡萄 active_model_serializers
【发布时间】:2015-09-23 19:39:35
【问题描述】:

我正在尝试使用葡萄和葡萄主动模型序列化器为我的 Rails 应用程序制作 V2 api。但我不知道如何为我的每个版本的 api 制作序列化程序。

这是我的 api 的样子

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

应用程序/序列化程序/v1

class UserSerializer < ActiveModel::Serializer
  include Serializer

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

应用程序/序列化程序/v2

class UserSerializer < ActiveModel::Serializer
  include Serializer

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

我添加到我的 config/application.rb

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

目前,V1 和 V2 用户控制器返回相同的 json,但没有电话号码和地址,我如何告诉我的 v2 api 使用 v2 序列化程序?

我正在使用grape、grape-active_model_serializers、grape-swagger 和grape-swagger-rails

【问题讨论】:

    标签: ruby-on-rails api active-model-serializers grape grape-api


    【解决方案1】:

    其实很简单,在我尝试过巫术和萨满教之后给我提示,如果你把你的序列化器分成可以正常工作的模块,那么现在我有

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

    和

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

    我之所以提出答案,是因为我看到很多关于序列化程序版本控制的问题,抱歉英语不好,但我没有土豆 -)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-12-06
      • 2015-06-13
      • 1970-01-01
      • 2013-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多