Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use helpers in a Grape API versus including a module?

Tags:

ruby

grape-api

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?

like image 695
huntmaster Avatar asked Jun 15 '16 14:06

huntmaster


1 Answers

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

like image 185
scorix Avatar answered Oct 18 '22 21:10

scorix