Module: Grape::DSL::Helpers::ClassMethods

Defined in:
lib/grape/dsl/helpers.rb

Instance Method Summary collapse

Instance Method Details

#helpers(new_mod = nil, &block) ⇒ Object

Add helper methods that will be accessible from any endpoint within this namespace (and child namespaces).

When called without a block, all known helpers within this scope are included.

Examples:

Define some helpers.


class ExampleAPI < Grape::API
  helpers do
    def current_user
      User.find_by_id(params[:token])
    end
  end
end

Parameters:

  • new_mod (Module) (defaults to: nil)

    optional module of methods to include

  • block (Block)

    optional block of methods to include


29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/grape/dsl/helpers.rb', line 29

def helpers(new_mod = nil, &block)
  if block_given? || new_mod
    mod = new_mod || Module.new
    define_boolean_in_mod(mod)
    inject_api_helpers_to_mod(mod) if new_mod

    inject_api_helpers_to_mod(mod) do
      mod.class_eval(&block)
    end if block_given?

    namespace_stackable(:helpers, mod)
  else
    mod = Module.new
    namespace_stackable(:helpers).each do |mod_to_include|
      mod.send :include, mod_to_include
    end
    change!
    mod
  end
end