Controllers
A controller is a class that inherits from Rocks::Controller. Each public method is
an action; it receives the request’s parameters as arguments and returns a Response.
class PostsController < Rocks::Controller def index: Response render :index, posts: Post.order(:created_at, :desc).all end
def show(id: Int): Response post = Post.find(id) return not_found unless post render :show, post: post # post is narrowed to Post here end
def create(post:: PostParams): Response record = Post.new(title: post.title, body: post.body)
if record.save redirect_to record, notice: "Post published." else render :new, post: record, status: :unprocessable_entity end endendParameters are arguments
Section titled “Parameters are arguments”Rails gives you a params hash and hopes for the best. Rocks binds request data
straight to your action’s parameters and converts it to their types:
- Positional parameters (
id: Int) come from the path or query string. - Keyword parameters (
post:: PostParams) come from the request body, bound to a struct or class by field name.
struct PostParams @[Required] property title: String
property body: String = ""endOnly the fields you declare are bound, so nobody can sneak admin: true into your
sign-up form. Rails calls this “strong parameters”. Rocks calls it “having types”.
A request that can’t be bound, such as /posts/banana for an Int id, gets a
400 Bad Request before your action runs.
Responses
Section titled “Responses”| Method | Sends |
|---|---|
render :view, **locals |
The view app/views/<controller>/<view>.facet, with locals |
render json: value |
value serialised as JSON |
redirect_to target |
A redirect to a path or a record |
head :no_content |
Just a status code |
not_found |
404 Not Found |
All of them accept status:, either as a number or as a symbol such as :created.
Filters
Section titled “Filters”Run code before or after actions with attributes:
@[Before(:require_login)]@[Before(:load_post, only: [:edit, :update, :destroy])]class PostsController < Rocks::Controller private def require_login: Response? redirect_to login_path unless current_user endendA before filter that returns a Response stops the request there; returning nil
lets it carry on. It’s a bouncer with a very clear policy.
Async actions
Section titled “Async actions”Actions can be async. Rocks awaits them for
you:
async def show(id: Int): Response weather = await WeatherService.fetch(id) render json: weatherend