Published on

How to Implement a Slack-like Dynamic Domains in Rails

Authors

Let say you want to automate your workflow.

Like everyone you might search, ask your friends/colleague to give you some recommendation.

After researching you've shortlisted the app list down to two.

Those two of them has same feature, design, pricing, everything else except User Experience (UX)

One has a Generic UX while the other is a personalised UX

Needless to say that we would go with the personalised app ?

What's better personalization than to offer an option to customized the sub-domain of our application to our customers.

Companies like Slack, BaseCamp does that :)

Here's how to setup and manage your Rails app to handle multiple subdomains.

Step 1 - Configure your DNS

All you need to do is set up a Wildcard A Recordand point it to your server.

Step 2 - Configure your Apache/ngix

We have configured our DNS to send all request to our server.

Now we need to handle it in the web server.

Here's the config for Apache (it just accepts all incoming request for that domain).

<VirtualHost *:80>
  ServerName example.com
  ServerAlias *.example.com
</VirtualHost>

Step 3 - Initialize Application Controller

class ApplicationController < ActionController::Base
  before_filter :set_current_account
    private
    def set_current_account
      @current_account = request.subdomains.first
    end
end

Step 4 - Custom Controller

class LoginController < ApplicationController
  def index
    render :json => @current_account
  end
end

That's it!

Let your customers have a subdomain.