grape的given
使用方式
given page: ->(v){v>1}, ref: ->(v){v=='history_price'} do
# ....
end
将
given
条件保存到dependent_on
# grape-1.5.3/lib/grape/dsl/parameters.rb
def given(*attrs, &block)
attrs.each do |attr|
proxy_attr = first_hash_key_or_param(attr)
raise Grape::Exceptions::UnknownParameter.new(proxy_attr) unless declared_param?(proxy_attr)
end
new_lateral_scope(dependent_on: attrs, &block)
end
检查
dependent_on
# grape-1.5.3/lib/grape/validations/params_scope.rb
def meets_dependency?(params, request_params)
return true unless @dependent_on
if @parent.present? && !@parent.meets_dependency?(@parent.params(request_params), request_params)
return false
end
return params.any? { |param| meets_dependency?(param, request_params) } if params.is_a?(Array)
# params might be anything what looks like a hash, so it must implement a `key?` method
return false unless params.respond_to?(:key?)
@dependent_on.each do |dependency|
if dependency.is_a?(Hash)
dependency_key = dependency.keys[0]
proc = dependency.values[0]
return false unless proc.call(params.try(:[], dependency_key))
elsif params.respond_to?(:key?) && params.try(:[], dependency).blank?
return false
end
end
true
end