Syro v3.2.0 Release Notes

Release Date: 2020-02-28 // almost 5 years ago

Previous changes from v3.1.0

  • ๐Ÿš€ This release adds status code handlers, a feature that will simplify many Syro applications.

    0๏ธโƒฃ When a request doesn't match, Syro will return a 404 status code with an empty body. It's a fine default because it doesn't make any assumptions, but in a production environment you want to return a helpful error message to the users. Up until now, the way to refine the 404 responses was to add a default block to each branch, for example:

    App = Syro.new do get do# ...end on "foo" do get do# ...end default do res.text "Not found!"endend default do res.text "Not found!"endend
    

    In that application, only two requests will return a status code 200: GET / and GET /foo. Any other request will return a 404 error with the body "Not found!".

    0๏ธโƒฃ We had to define a default block for each branch, and if we want to deal with 404 status codes in a different way we can install a handler. The new version would look like this:

    App = Syro.new do handle 404 do res.text "Not found!"end get do# ...end on "foo" do get do# ...endendend
    

    The external behavior will be the same, but the solution is perhaps more elegant. At any point, and in any branch, the handler can be replaced. For example, let's say you want a different error message when a user is not found:

    App = Syro.new do handle 404 do res.text "Not found!"end# ... on "users" do on :id do handle 404 do res.text "User not found"end# ...endendend
    

    You can think about handlers as filters that will get executed just before finishing the request. Within those handlers you can do anything you would do in a regular block, for instance:

    App = Syro.new do handle 404 do res.redirect "/wiki"end on "wiki" do# ...endend
    

    ๐ŸŽ In this last example, the res.redirect statement will change the status code to 302. You can also add handlers for other status codes besides 404. You could even add handlers for status 200, but in that case, as it involves an extra method call, you will get a slight performance penalty.

    ๐Ÿ“š The documentation covers other use cases and some edge conditions that you can abuse. Let me know if you run into any issues or if you detect something that's not clear enough.

    ๐Ÿ’Ž Note: as the implementation uses the safe navigation operator &., Ruby > 2.3 is required to run this version.