Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to put constraint classes in Rails project

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?

like image 439
at. Avatar asked Oct 23 '12 18:10

at.


People also ask

What are Rails constraints?

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.

How do I see all routes in Rails?

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.

What are restful routes in Rails?

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.

What is namespace in Rails 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.


1 Answers

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
like image 83
axsuul Avatar answered Sep 27 '22 03:09

axsuul