Skip to content

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.

app/controllers/posts_controller.am
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
end
end

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.
app/params/post_params.am
struct PostParams
@[Required]
property title: String
property body: String = ""
end

Only 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.

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.

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
end
end

A 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.

Actions can be async. Rocks awaits them for you:

async def show(id: Int): Response
weather = await WeatherService.fetch(id)
render json: weather
end