Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Configure dynamic assets_host in Rails 3

I want Rails 3 to dynamically grab assets depending on current domain:

mysite.com - assets.mysite.com mysite.ru - assets.mysite.ru

Is it possible out of the box? Or I should implement it manually?

like image 918
Oksana Avatar asked Dec 02 '22 04:12

Oksana


2 Answers

Try sending a proc to asset_host, which yields both the asset path and request:

config.action_controller.asset_host = proc {|path, request|
  "http://assets." << request.host
}
like image 150
Richard Johansson Avatar answered Dec 07 '22 22:12

Richard Johansson


Note the key differences from other solutions in the solutions below:

  1. Using request.domain instead of request.host since most assets hosts would not be assets0.www.domain.com but rather assets0.domain.com
  2. Using the source.dash and modulo will ensure that the same asset is served from the same asset server. This is key for page performance.
  3. Filtering by asset type/path.

I have always done something like this:

  config.action_controller.asset_host = Proc.new { |source, request|
    "http#{request.ssl? ? 's' : ''}://cdn#{(source.hash % 3)}." << request.domain # cdn0-3.domain.com
  }

Or if you have multiple asset/cdn hosts you could decide to be selective about what kind of assets are served from what host like so:

config.action_controller.asset_host = Proc.new { |source, request|
  case source
  when /^\/images/
    "http#{request.ssl? ? 's' : ''}://cdn#{(source.hash % 2)}." << request.domain # cdn0-1.domain.com
  when /^\/javascripts/, /^\/stylesheets/
    "http#{request.ssl? ? 's' : ''}://cdn#{(source.hash % 2) + 2}." << request.domain # cdn2-3.domain.com
  else
    "http#{request.ssl? ? 's' : ''}://cdn4." << request.domain # cdn4.domain.com
  end
}

Hope this helps!

like image 29
PeppyHeppy Avatar answered Dec 07 '22 22:12

PeppyHeppy