Skip to content

Controllers

Alexander Popov edited this page Feb 9, 2021 · 2 revisions

End-points

Public non-inherited instance methods are application actions (end-points).

Hooks

Protected #execute method is a wrapper for any action execute, action-name (method-name) is the only argument.

In this method you can write or invoke before-hooks, then call super (which will also call ancestors #execute method, and only at the end target-method call), and after super you can write (or invoke) after-hooks.

#execute method can be mixed by include (I don't recommend prepend because it allows to have the same module multiple times in the ancestors, i.e. end-point call chain).

Errors

You can handle errors by protected #server_error method with exception argument (calling super is recommended).

def index(method)
  raise 'Error'
end

protected

def server_error(exception) # => 'Error'
  @my_var = true
  super # for rendering default_body response with @my_var
end

Helpers

Private methods are just helpers (#model_params, for example).

Modules

If you want to take out some scope of helpers (typically for reusing them in different controllers) — check Helpers wiki page.

Built-in

Get current response body: body. Set: body 'New body'.

status works in the same way.

There are also Hash-like request.headers, response.headers, cookies and session.

view or render (alias) receives file-name of template as String or Symbol and options for Tilt, and returns rendered file as a String.

path_to method is for path building to any controller and its action: path_to ArticlesController, :show, id: 2 gives path to ArticlesController#show(id) with id 2.

Return value of called action (end-point) will be a body of the response, but can be changed in after-hooks (code after super inside #execute).