当使用Grape编写应用程序接口时,为什么要麻烦地使用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但是,为什么不这样做呢?
class IncludeAPI < Grape::API
include HelperMethods
get 'do_stuff/:id' do
useful_method(params[:id])
end
end我猜包含HelperMethods模块的目的是为了提供帮助方法这一点更明确一些,但这似乎是添加替代语法的一个软弱的理由。
与仅使用普通include相比,您希望使用helpers的好处/原因是什么
发布于 2016-06-15 23:03:03
你可以使用辅助函数来定义可重用的参数,这在标准的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
endhttps://stackoverflow.com/questions/37838438
复制相似问题