编写带有葡萄的API时,为什么要使用helpers
宏观,而不是包括模块或添加方法?
例如,您可以在模块中定义方法,并将其作为葡萄的助手包括在内:
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
但是,为什么不这样做呢?
class IncludeAPI < Grape::API
include HelperMethods
get 'do_stuff/:id' do
useful_method(params[:id])
end
end
我猜想将HelperMethods
模块包括在内,这是提供辅助方法的情况,但这似乎是添加替代语法的薄弱理由。
您要使用helpers
而不是正常的include
有什么好处/原因?
您可以使用助手来定义可重复使用的参数,而助手可以在标准红宝石模块中执行此操作。
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
https://github.com/ruby-grape/grape#helpers