-
Notifications
You must be signed in to change notification settings - Fork 0
Controllers
Controllers are classes where all your application's business logic resides. To add a new controller to Racket, you need to do two things:
1. Create a class that inherits from Racket::Controller
class MyFirstController < Racket::Controller
# controller code omitted
endThe name of the Controller class does not matter, you can name it anything you want as long as it inherits from Racket::Controller.
If you want your controllers to have some common functionality that is not provided by Racket::Controller, you can create a custom controller class and inherit from it instead.
class BaseController < Racket::Controller
def special_sauce
'special sauce'
end
end
class MyController < BaseController
# controller code omitted
end2. Place the file where you saved your controller class somewhere below the controller root directory. The controller root directory can be configured the be anywhere in the file system, but by default it is set to the directory controllers in your application directory. Typically, your file hierarchy looks something like this:
application_directory/
config.ru
controllers/
my_first_controller.rb
foo/
foo_controller.rb
The placement of your controller file is very important when using Racket since it is the single piece of information that Racket uses to decide which routes (URLs) the controller should handle. It works like this:
- A controller file placed directly in
controllershandles all URLs beginning with/. - A controller file placed in
controllers/foohandles all URLs beginning with/foo. - A controller file placed in
controllers/foo/barhandles all URLs beginning with/foo/bar.
"Longer" URLs are always processed first, meaning that if a request for /foo/bar comes in it will be processed by the controller at controllers/foo/bar, not by the controller at controllers/foo. However, if you have not defined a controller for /foo/bar, the request will automatically propagate "upwards" to the controller handling /foo. And if that does not exist either, the request will propagate again to the controller handling /. In theory this means you only need one controller to handle all requests (just by putting it directly in controllers), but for most applications you are probably better of having different controllers handling different URLs.
This "magic" mapping between controller file location and the routes your controller is handling also means you have to be careful about what files you place in the controllers directory. controllers and all subdirectories below it should contain at most one controller file, otherwise your requests might be routed somewhere unexpected. (This includes the case where you want to have a "base controller class". At the moment you need to place such a class outside the controllers directory and require it manually. I consider this a design flaw though, so later versions of Racket might allow this.)