Joe Half Face
Joe Half Face

Reputation: 2333

Grape: dynamic prefix?

I have api set up like this:

class Dashboard < Api
  def self.inherited(subclass)
    super
    subclass.instance_eval do
      prefix 'dashboard'
      #...
    end
  end

  def self.company_id(path)
    ':company_id' + path
  end

  helpers do
    def current_company
      @current_company ||= Company.find(params[:company_id]) if params[:company_id]
    end
  end
end

Problem: I inherit class Employee from Dashboard, and what I want to achieve: resource, which inherits from Dashboard, should be accessed by it's namespace '/dashboard/companies/:company_id/employees', with current_company working correct.

I feel tiring each time to provide full route instead of namespace convenience:

get 'companies/:company_id/employees'
#...
end

But this won't give result needed:

namespace :companies do
  namespace :employees do
  ...
  end 
end

Upvotes: 0

Views: 328

Answers (1)

P&#233;ha
P&#233;ha

Reputation: 2933

From what I undertand, you're looking for dynamic namespace, isn't it? You can define dynamic namespaces using a string instead of just a symbol. In the given string, each :something part indicates a parameter, same thing as what you may be used to in Rails or Sinatra routes syntax. In the endpoints, you'll then be able to access params[:something] as you usually do.

For instance, in your case, you might use something like this :

namespace 'companies/:company_id' do
  namespace :employees do
    get do
      # Will respond with the available params (containing :company_id)
      body params
    end
  end
end

Upvotes: 0

Related Questions