Why use helpers in a Grape API versus including a module?
Asked Answered
C

1

8

When writing an API with Grape, why bother using the helpers macro, versus just including a module, or adding a method?

For example, you can define methods in a module and include them as helpers in Grape like so:

module HelperMethods
  def useful_method(param)
    "Does a thing with #{param}"
  end
end

class HelpersAPI < Grape::API
  helpers HelperMethods

  get 'do_stuff/:id' do
    useful_method(params[:id])
  end
end

But, why not just do this?

class IncludeAPI < Grape::API
  include HelperMethods

  get 'do_stuff/:id' do
    useful_method(params[:id])
  end
end

I guess it's a little more explicit that you're including the HelperMethods module for the purpose of providing helper methods, but that seems like a weak reason to add an alternative syntax.

What are the benefits/reasons that you would want to use helpers versus just a normal include?

Capriole answered 15/6, 2016 at 14:33 Comment(2)
IIRC, helpers includes the module in nested namespaces, too.Cinquecento
That's fine, but you can do that with modules as well, just by using a standard module pattern of the top level module requiring it's nested modules. Less surprising that way too.Capriole
C
3

You can define reusable params using helpers which you can't do this in a standard ruby module.

class API < Grape::API
  helpers do
    params :pagination do
      optional :page, type: Integer
      optional :per_page, type: Integer
    end
  end

  desc 'Get collection'
  params do
    use :pagination # aliases: includes, use_scope
  end
  get do
    Collection.page(params[:page]).per(params[:per_page])
  end
end

https://github.com/ruby-grape/grape#helpers

Crosslet answered 15/6, 2016 at 15:3 Comment(1)
That's fine, but why would I ever use it for methods? My example isn't setting parameters with the helper macro.Capriole

© 2022 - 2024 — McMap. All rights reserved.