Skip to content
Peter Kappus edited this page Mar 3, 2018 · 5 revisions

Controllers

Amethyst controllers are classes with method-based actions. The name of any controller must be like NameController, and it must be inherited from Base::Controller. Here is an example of simple Amethyst controller:

require "../src/amethyst"

class IndexController < Base::Controller
  actions :hello, :bye

  def hello #hello action
    html "<p>Hello, you're asked a #{request.method} #{request.path}</p> \n
          <a href='/bye'>Visit <b>bye</b> action</a>
          <img src='/images/amethyst.jpg'>"
  end

  def bye   #bye action
    text "Bye! We hope you will come back"
  end
end

Controllers must be later registered in application.

Actions

Controllers describe actions as a methods. You should specify your actions methods next way:

actions :hello, :bye

This lets app to know which methods of your contoller are actions, and which aren't.

Request and response objects

Inside a controller, you have acces to request and response objects:

def hello
    html "<p>Hello, you're asked a #{request.method} #{request.path}</p> \n
          <a href='/bye'>Visit <b>bye</b> action</a>
          <img src='/images/amethyst.jpg'>"
end

You use your actions to describe a routes for your application.

Parameters

Amethyst doing all work about handling requests and responses and their parameters for you automatically. Request has Rails-like named methods for accessing request parameters objects:

  • request.query_parameters - for GET params
  • request.request_parameters - for POST params
  • request.path_parameters - "captured" parts of path matched with a route (for example, path /user/1/ matches route /users/:id, and id will be 1).

All these objects are hashes of parameter name and its value.

Helpers

Inside actions you can use various helpers (the list will be expanding):

  • html(string : String) - renders html code from string
  • text(string : String) - renders plain text from string
  • json(string : String) - renders json from string
  • response.set_cookie(cookie_string : String) - sets cookie from string
Clone this wiki locally