2

Is there any way that I can common header in Rails with Grape so I do not have to specify the same header over and over again?

namespace :user do
  desc 'Return a user.', {
    headers: {
      "Authorization" => {
        description: "Some Token",
        required: true
      }
    }
  }
  get do
    {}
  end
end

Notice that headers would have to be specified over and over in all my APIs since I want them to be secure. Is there a shortcut way (a design pattern) that I can follow without creating this header everytime?

And no I am not looking for something like this:

def headers
  {
    "Authorization" => {
      description: "Some Token",
      required: true
    }
  }
end

namespace :user do
  desc 'Return a user.', {
    headers: headers
  }
  get do
    {}
  end
end
max pleaner
  • 26,189
  • 9
  • 66
  • 118
user3019766
  • 131
  • 1
  • 10
  • 2
    Why is the `def headers` example not good? You're discounting this option too quickly. You can always make the method take arguments and merge them into the result hash. – max pleaner Aug 13 '16 at 01:18
  • A design pattern you could use is inheritance.Create a base class that always implements the Authorization header and extend from that. – Rots Aug 13 '16 at 02:41

2 Answers2

1

This is what I did:

app/api/api.rb

def my_headers
  {
    key1: {
      description: 'hello',
      required: true
    },
    key2: {
      description: 'hello',
      required: false
    }
  }
end

# define my_headers outside of API class

class API < Grape::API
  version 'v1', using: :param, parameter: 'v', vendor: 'Larvata'
  content_type :json, 'application/json'

  # some codes ...

app/api/home.rb

class Home < API

 resources :home do

    desc "Home Page", { headers: my_headers }
    get do
      # some codes ...

oh, sorry, you are looking for this solution ...

zx1986
  • 880
  • 2
  • 12
  • 18
1

This worked well.
You can add class method that returns header definitions to api root class and call it from each api class.

app/api/root.rb

module Api
  class Root < Grape::API
    def self.headers_definition
      {
        "Authorization" => {
          description: "Some Token",
          required: true
        }
      }
    end

    mount Home
  end
end

app/api/home.rb

module Api
  class Home < Grape::API
    resources :home do

      desc "Home Page", headers: Root.headers_definition
        get do
         # some codes ...
        end
      end  
    end
  end
end
utwang
  • 1,474
  • 11
  • 16