Ruby 如何为多条路线编写相同的要求,例如POST、PUT?(红宝石葡萄)
如何避免重复代码Ruby 如何为多条路线编写相同的要求,例如POST、PUT?(红宝石葡萄),ruby,grape-api,Ruby,Grape Api,如何避免重复代码 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: dateRe
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
试试这个:
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
在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
语句,可以混合不同的参数组。我得到一个错误ArgumentError-参数数目错误(1代表0):
我使用的是grape 0.10.1。您使用的是哪个版本?你应该这样做<代码>类API