Where to put constraint classes in Rails project Where to put constraint classes in Rails project ruby-on-rails ruby-on-rails

Where to put constraint classes in Rails project


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  endend

and in your routes.rb

constraints Constraint::Authenticated.new do  match 'account' => 'account#index'end


This is strange that the guide says nothing about that path, but lib/constraints is even listed in the API (ActionDispatch::Routing::Mapper::Scoping):

You are able to move this logic out into a class if it is too complex for routes. This class must have a matches? method defined on it which either returns true if the user should be given access to that route, or false if the user should not.

class Iphone  def self.matches?(request)    request.env["HTTP_USER_AGENT"] =~ /iPhone/  endend

An expected place for this code would be lib/constraints.