为什么在 Grape API 中使用助手而不是包含模块?

hun*_*ter 6 ruby grape-api

当使用 Grape 编写 API 时,为什么要费心使用helpers宏,而不是仅仅包含一个模块或添加一个方法?

例如,您可以在模块中定义方法并将它们作为帮助程序包含在 Grape 中,如下所示:

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
Run Code Online (Sandbox Code Playgroud)

但是,为什么不这样做呢?

class IncludeAPI < Grape::API
  include HelperMethods

  get 'do_stuff/:id' do
    useful_method(params[:id])
  end
end
Run Code Online (Sandbox Code Playgroud)

我想您HelperMethods为了提供辅助方法而包含该模块更为明确,但这似乎是添加替代语法的一个微不足道的理由。

helpers与只是普通的相比,您想要使用的好处/原因是include什么?

sco*_*rix 2

您可以使用助手定义可重用的参数,但在标准 ruby​​ 模块中无法做到这一点。

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
Run Code Online (Sandbox Code Playgroud)

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