4

如何避免重复代码?

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
4

2 回答 2

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为不同的命名参数包含多个语句来混合不同的参数组。

于 2014-09-16T17:18:15.183 回答
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
于 2013-05-23T09:34:56.807 回答