Dynamic cookie domain (for multitenant app)

There is a Multitenant App, that should serve sites on domains like
And it's easy to share cookies between all of them (using '.app.com'
cookie domain):
  ActionController::Base.session = {:key => thekey, :secret =>
thesecret, :domain => '.app.com'}

But! There is one more requirement, those sites should be also avaliable

So, in order to all this works the App should dynamically change the
cookie domain:
  xxx.app.com => ".app.com"
  www.xxx.com => ".xxx.com" or leave it blank

Google told me that there is one approach
but it doesn't works (Rails 2.3.5).

I also tried my own solution:

  class CrossDomainCookies
    def initialize(app)
      @app = app

    def call(env)
      host = env["HTTP_HOST"].split(':').first.downcase
      if host.include?('.')
        normalized_host = host.scan(/[^\.]+\.[^\.]+$/).first
        cookie_domain = ".#{normalized_host}"
        normalized_host = host
        cookie_domain = host

      Rails.logger.info cookie_domain

      ActionController::Base.session_options['domain'] = cookie_domain


But it also doesn't works, maybe there are some other solutions?