目标:使用辅助模块中的 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
调用从 A
和 B
移动到 API< 时出现问题
挂载它们的类,抛出异常:
block (2 levels) in use': Params :requires_authentication_params not found! (RuntimeError)
有趣的是,该模块确实包含在内,因为如果我向类 V1::Helpers
添加任何实例方法,我就可以在 A
和 B
.
那么问题是,DRY this 并遵循最佳实践的最佳解决方案是什么?
最佳答案
如果您在 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
关于ruby-on-rails - Rails Grape,DRY Helpers 调用共享参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26854599/