1

I have a custom Grape DSL method called scope that remembers the parameter then delegates some work to the params helper.

class API::V1::Walruses < Grape::API
  resources :walruses do
    scope :with_tusks, type: Integer,
     desc: "Return walruses with the exact number of tusks"
    scope :by_name, type: String,
     desc: "Return walruses whose name matches the supplied parameter"

    get do
      # Equivalent to `Walrus.with_tusks(params[:with_tusks]).
      # by_name(params[:by_name])`, but only calls scopes whose
      # corresponding param was passed in.
      apply_scopes(Walrus)
    end
  end
end

This works and is clean, which I like. The problem is that many child endpoints also want to use those same scopes. This means maintaining them in multiple places and keeping them all in sync.

I would like to do the following instead:

class API::V1::Walruses < Grape::API
  helpers do
    scopes :index do
      scope :with_tusks, type: Integer,
       desc: "Return walruses with the exact number of tusks"
      scope :by_name, type: String,
       desc: "Return walruses whose name matches the supplied parameter"
    end
  end
  resources :walruses do
    use_scopes :index
   #...
  end
end

Then API::V1::Walruses will have those scopes available, as will API::V1::Walruses::Analytics (if included), and any others that are nested within.

Params have a similar methodology but I've had trouble understanding how to inherit settings.

Chris
  • 11,819
  • 19
  • 91
  • 145
  • 1
    Is there anything else that's done by `scope` other than do some `params`? If so params support `use :params_by_name` where `:params_by_name` is defined in a `helpers` block. I think otherwise it's really about copy-pasting how params behave, it's a little long to explain all the inheritance logic, it's quite thick (and I didn't write it ;)). – dB. Aug 31 '15 at 13:41
  • Thanks @dB! It also saves the scope name so that `apply_scopes` knows which scopes are enabled. There are additional options as well. I'll look at copying params and starting from there. Thanks! – Chris Aug 31 '15 at 18:22

0 Answers0