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

时间:2016-06-15 14:33:53

标签: 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

但是,为什么不这样做?

class IncludeAPI < Grape::API
  include HelperMethods

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

我想,为了提供帮助方法,你更明确地包括HelperMethods模块,但这似乎是添加替代语法的一个弱理由。

您希望使用helpers与普通include相比有哪些好处/原因?

1 个答案:

答案 0 :(得分:1)

您可以使用帮助程序定义可重用的参数,而不能在标准的ruby模块中执行此操作。

SUBSTR(string, INSTR(string,'/',1,2) + 1, INSTR(string,'/',1,4) - INSTR(string,'/',1,2)-1)

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