如何为多个路由编写相同的要求,例如POST,PUT? (红宝石葡萄)

时间:2013-05-23 09:23:14

标签: 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: 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

2 个答案:

答案 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