ruby-on-railsruby-on-rails-3naming-conventionsruby-on-rails-3.2convention-over-configur

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?


Solution

  • 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