hanami / api

Minimal, lightweight, fastest Ruby framework for HTTP APIs.
https://hanamirb.org
MIT License
350 stars 13 forks source link

Block helpers #26

Closed jodosha closed 3 years ago

jodosha commented 3 years ago

Define helper methods available within the block context. Helper methods have access to default utilities available in block context (e.g. #halt).

Helpers can be defined inline, by passing a block to the .helpers method:

require "hanami/api"

class MyAPI < Hanami::API
  helpers do
    def redirect_to_root
      # redirect method is provider by Hanami::API block context
      redirect "/"
    end
  end

  root { "Hello, World" }

  get "/legacy" do
    redirect_to_root
  end
end

Alternatively, .helpers accepts a module.

require "hanami/api"

class MyAPI < Hanami::API
  module Authentication
    private

    def unauthorized
      halt(401)
    end
  end

  helpers(Authentication)

  root { "Hello, World" }

  get "/secrets" do
    unauthorized
  end
end

You can use .helpers multiple times in the same app.


Closes https://github.com/hanami/api/issues/25