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开发者_Go百科 manually?
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
}
Note the key differences from other solutions in the solutions below:
- Using request.domain instead of request.host since most assets hosts would not be assets0.www.domain.com but rather assets0.domain.com
- 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.
- 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!
Are you meaning subdomains?
subdomains(tld_length = 1)
Returns all the subdomains as an array, so ["dev", "www"] would be returned for “dev.www.rubyonrails.org“. You can specify a different tld_length, such as 2 to catch ["www"] instead of ["www", "rubyonrails"] in “www.rubyonrails.co.uk“.
In config/environments/production.rb etc.
config.action_controller.asset_host = "http://assets." << request.host
精彩评论