-
Notifications
You must be signed in to change notification settings - Fork 46
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.
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.
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.
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
- forGET
params -
request.request_parameters
- forPOST
params -
request.path_parameters
- "captured" parts of path matched with a route (for example, path/user/1/
matches route/users/:id
, andid
will be1
).
All these objects are hashes of parameter name and its value.
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