Just curious about the best practices for Rails in where I put a custom constraints class that's used as a constraint in config/routes.rb. Seems like Rails.root/lib
is where all user classes go. Is that appropriate for this? Should I be creating a directory inside for constraints? 2 empty directories exist there now, assets
and tasks
. Are there conventions for this?
Routing constraints are checks written around routes that will clean and validate information before even hitting a controller action. The key word here is before. Before this external data can touch behavior in your controllers, and subsequently your persistence layers, it already gets vetted.
TIP: If you ever want to list all the routes of your application you can use rails routes on your terminal and if you want to list routes of a specific resource, you can use rails routes | grep hotel . This will list all the routes of Hotel.
The Rails router is responsible for redirecting incoming requests to controller actions. The routing module provides URL rewriting in native Ruby. It recognizes URLs and dispatches them as defined in config/routes.
This is the simple option. When you use namespace , it will prefix the URL path for the specified resources, and try to locate the controller under a module named in the same manner as the namespace.
lib/
would be the appropriate place. If you want to make it cleaner, put it in lib/constraint/authenticated.rb
and define your constraints like so
module Constraint
class Authenticated
def matches?(request)
# stuff
end
end
end
and in your routes.rb
constraints Constraint::Authenticated.new do
match 'account' => 'account#index'
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With