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
?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With