Skip to main content

Rails - Complex Route Constraints Made Easy

In Rails, we know that the routes are the most important entry-point where we define the which url hits which controller. We also know how to define the resources and add some conditions to the routing.

In this post, I want to concentrate about how to go about complex route conditions and make it easy for you to write modular code.

Let's say that you have to write a condition that if the domain belongs to a given domain, route the root url to some other controller. You can accomplish it using the following snippets:

Here you are creating a class for the domain constraint and having the required method called matches? which does the computing on the fly.

class DomainConstraint
  def initialize(domain)
    @domains = [domain].flatten

  def matches?(request)
    @domains.include? request.domain
Now you add the code to the routes.rb as following:

constraints'') do
  root :to => 'mydomain#index'
The above code makes sure that the requests coming to a will have a root url at the mydomain controller and index action!

Happy Railing!

Follow me on TwitterFacebookLinkedIn, Instagram or Website.



You are in a cold conference room, Do you want to use your mac as a heater?

Imagine that you are in cold conference room and you kind of feeling the cold on your head. What do you do when you are in a serious meeting and just can't get out?

If you have a MacBook, you might have a solution.

Use your terminal to run either of these commands to keep your CPU at above 80% or if you want you can run them both.

$ openssl speed


$ yes > /dev/null

The first command just outputs the ssl cryptography stats and it keeps your cpu busy. The second command just prints the character "y" into IO.

So try it out and let me know how it works! :D

Talk to me on Twitter, Facebook, LinkedIn or Website