Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write same requirements for multiple routes e.g. POST, PUT? (Ruby Grape)

Tags:

ruby

grape-api

How can I avoid duplicate code?

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
like image 749
hfossli Avatar asked Jan 13 '23 07:01

hfossli


1 Answers

In more recent versions of Grape, you can create reusable named groups of parameters. For example:

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

One advantage of doing things this way is that you can mix different groups of parameters by including multiple use statements for different named params.

like image 126
Matt Zukowski Avatar answered Feb 07 '23 02:02

Matt Zukowski