当使用 Grape 编写 API 时,为什么要费心使用helpers宏,而不是仅仅包含一个模块或添加一个方法?
例如,您可以在模块中定义方法并将它们作为帮助程序包含在 Grape 中,如下所示:
module HelperMethods
def useful_method(param)
"Does a thing with #{param}"
end
end
class HelpersAPI < Grape::API
helpers HelperMethods
get 'do_stuff/:id' do
useful_method(params[:id])
end
end
Run Code Online (Sandbox Code Playgroud)
但是,为什么不这样做呢?
class IncludeAPI < Grape::API
include HelperMethods
get 'do_stuff/:id' do
useful_method(params[:id])
end
end
Run Code Online (Sandbox Code Playgroud)
我想您HelperMethods为了提供辅助方法而包含该模块更为明确,但这似乎是添加替代语法的一个微不足道的理由。
helpers与只是普通的相比,您想要使用的好处/原因是include什么?
您可以使用助手定义可重用的参数,但在标准 ruby 模块中无法做到这一点。
class API < Grape::API
helpers do
params :pagination do
optional :page, type: Integer
optional :per_page, type: Integer
end
end
desc 'Get collection'
params do
use :pagination # aliases: includes, use_scope
end
get do
Collection.page(params[:page]).per(params[:per_page])
end
end
Run Code Online (Sandbox Code Playgroud)
https://github.com/ruby-grape/grape#helpers
| 归档时间: |
|
| 查看次数: |
2975 次 |
| 最近记录: |