将参数从 Grape::API 传递到序列化程序

Pass Parameters from Grape::API to Serializer

我正在获取一个参数,例如:member_id in Grape::API like

   desc 'Return Events'
         params do
             requires :member_id, type: Integer, desc: 'Member'
         end
         get 'all' do
              #some code
         end
     end

我想将它传递给 ActiveModel::Serializer 以便我可以执行一些功能。

有什么方法可以将它传递给 ActiveModel::Serializer

当您使用 ActiveModel::Serializers 序列化一个对象时,您可以将序列化程序内部可用的选项作为 options(或 instance_options,或 contextdepending on which version of AMS you're using).

例如,在 Rails 中,您将像这样传递一个 foo 选项:

# 0.8.x or 0.10.x
render @my_model, foo: true
MyModelSerializer.new(@my_model, foo: true).as_json

# 0.9.x
render @my_model, context: { foo: true }
MyModelSerializer.new(@my_model, context: { foo: true }).as_json

在您的序列化程序中,您访问 options(或 instance_options)以获取值:

class MyModelSerializer < ActiveModel::Serializer
  attributes :my_attribute

  def my_attribute
    # 0.8.x: options
    # 0.9.x: context
    # 0.10.x: instance_options
    if options[:foo] == true
      "foo was set"
    end
  end
def