ruby-on-rails - Rails Grape,DRY Helpers 调用共享参数

标签 ruby-on-rails ruby helpers grape-api

目标:使用辅助模块中的 grape 共享参数,而无需在每个已安装的 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 this 并遵循最佳实践的最佳解决方案是什么?

最佳答案

如果您在 API 上包含 V1::Helpers,然后让 AB 继承自 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

关于ruby-on-rails - Rails Grape,DRY Helpers 调用共享参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26854599/

相关文章:

ruby-on-rails - rails 3.1 : Better way to expose an engine's helper within the client app

ruby-on-rails - Devise - 确认后重定向到重发确认指令页面

ruby - 使用子类中的常量在父类中定义 attr_accessor

ruby - XML 到哈希转换 : Nori drops the attributes of the deepest XML elements

ruby - Ruby 元模型

nested - 如何在 Handlebars 中使用多个助手

ruby-on-rails - 自定义表单助手

ruby-on-rails - 如何更改关联的验证错误消息?

ruby-on-rails - Ruby on Rails - 父级和子级之间的链接 - 没有路由匹配 [POST]

ruby-on-rails - Ruby on Rails : Active Record query fails to execute only when hosted on heroku.