Rails Grape,DRY Helpers共享参数的调用

6

目标:使用葡萄 Shared Params 助手模块,无需在每个安装的 API 上添加语法 helpers Helper::Module

有效示例代码:

# /app/api/v1/helpers.rb
module V1
  module Helpers
    extend Grape::API::Helpers

    params :requires_authentication_params do
      requires :user_email,           type: String
      requires :authentication_token, type: String
    end
  end
end

# /app/api/api.rb
class API < Grape::API
  format :json
  version 'v1', using: :path

  mount V1::A
  mount V1::B
end

# /app/api/v1/a.rb
module V1
  class A < Grape::API
    helpers V1::Helpers

    desc 'SampleA'
    params do
      use :requires_authentication_params
    end
    get 'sample_a/url' do
      #...
    end
  end
end

# /app/api/v1/B.rb
module V1
  class B < Grape::API
    helpers V1::Helpers

    desc 'SampleB'
    params do
      use :requires_authentication_params
    end
    get 'sample_b/url' do
      #...
    end
  end
end

当我试图将helpers V1::Helpers的调用从AB移动到安装它们的API类时,出现了问题,抛出了异常:

block (2 levels) in use': Params :requires_authentication_params not found! (RuntimeError)

作为一个有趣的注记,该模块被包含了进来,因为如果我给类V1 :: Helpers 添加任何实例方法,我就可以在AB内部使用它们。
那么问题是,什么是最好的解决方案来DRY化并遵循最佳实践?
1个回答

0
如果您在API上包含V1 :: Helpers,然后使A和B从API继承,会发生什么?例如:
# /app/api/api.rb
class API < Grape::API
  include V1::Helpers

  format :json
  version 'v1', using: :path

  mount V1::A
  mount V1::B
end

class A < API
  # ...
end

class B < API
  # ...
end

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接