如何避免重复代码?
resource 'api/publication/:publicationName' do
params do
requires :type, type: String, regexp: /^(static|dynamic)$/i
requires :name, type: String, regexp: /^[a-z0-9_\s]+$/i
requires :liveStartDate, type: String, regexp: dateRegexp
optional :liveEndDate, type: String, regexp: dateRegexp
requires :query, type: String
end
post '/dynamic' do
authenticate!
save_or_update(params)
end
params do
requires :type, type: String, regexp: /^(static|dynamic)$/i
requires :name, type: String, regexp: /^[a-z0-9_\s]+$/i
requires :liveStartDate, type: String, regexp: dateRegexp
optional :liveEndDate, type: String, regexp: dateRegexp
requires :query, type: String
end
put '/dynamic/:id' do
authenticate!
save_or_update(params)
end
end
答案 0 :(得分:6)
在更新的Grape版本中,您可以创建可重复使用的命名参数组。例如:
resource 'api/publication/:publicationName' do
helpers do
params :common do
requires :type, type: String, regexp: /^(static|dynamic)$/i
requires :name, type: String, regexp: /^[a-z0-9_\s]+$/i
requires :liveStartDate, type: String, regexp: dateRegexp
optional :liveEndDate, type: String, regexp: dateRegexp
requires :query, type: String
end
end
params do
use :common
end
post '/dynamic' do
authenticate!
save_or_update(params)
end
params do
use :common
end
put '/dynamic/:id' do
authenticate!
save_or_update(params)
end
end
以这种方式执行操作的一个优点是,您可以通过为不同的命名参数包含多个use
语句来混合不同的参数组。
答案 1 :(得分:3)
试试这个:
resource 'api/publication/:publicationName' do
common_params = Proc.new do
requires :type, type: String, regexp: /^(static|dynamic)$/i
requires :name, type: String, regexp: /^[a-z0-9_\s]+$/i
requires :liveStartDate, type: String, regexp: dateRegexp
optional :liveEndDate, type: String, regexp: dateRegexp
requires :query, type: String
end
params(&common_params)
post '/dynamic' do
authenticate!
save_or_update(params)
end
params(&common_params)
put '/dynamic/:id' do
authenticate!
save_or_update(params)
end
end