我有一个名为scope
的自定义Grape DSL方法,它会记住该参数,然后将一些工作委托给params
帮助程序。
class API::V1::Walruses < Grape::API
resources :walruses do
scope :with_tusks, type: Integer,
desc: "Return walruses with the exact number of tusks"
scope :by_name, type: String,
desc: "Return walruses whose name matches the supplied parameter"
get do
# Equivalent to `Walrus.with_tusks(params[:with_tusks]).
# by_name(params[:by_name])`, but only calls scopes whose
# corresponding param was passed in.
apply_scopes(Walrus)
end
end
end
这很有效,很干净,我喜欢。问题是许多子端点也想使用那些相同的范围。这意味着将它们保存在多个位置并使它们保持同步。
我想改为:
class API::V1::Walruses < Grape::API
helpers do
scopes :index do
scope :with_tusks, type: Integer,
desc: "Return walruses with the exact number of tusks"
scope :by_name, type: String,
desc: "Return walruses whose name matches the supplied parameter"
end
end
resources :walruses do
use_scopes :index
#...
end
end
然后API::V1::Walruses
将提供这些范围,API::V1::Walruses::Analytics
(如果包含)以及嵌套在其中的任何其他范围。
Params有类似的方法,但我无法理解如何继承设置。