Dynamically set a domain for a Rails asset host

March 14, 2009

 
No Gravatar

I’ve been wanting to implement an asset host for my Rails app, looking over the API I saw that Rails’ asset_host only supported a single domain. I’m running multiple domains off one Rails app, so this would have been a problem. After a little research, I came up with a solution that would work for me.

I run this as a before_filter in my Application Controller.

# for my use, @site.domain returns the user's current
# domain. you should change this to whatever method
# you use to get the domain
 
class ApplicationController < ActionController::Base
before_filter :find_asset_host
 
private
 
  def find_asset_host
    ActionController::Base.asset_host = Proc.new { |source|
        asset_hosts = %w{icarus zeus aphrodite etc etc}
 
        # disable asset host for development 
        if is_development?
          ""
        else
          "http://#{asset_hosts[rand(4)]}.#{@site.domain}"
        end
      }    
  end
 
end
  • You set your hosts in the hash.
  • Lin
    It's really cool. Does it mean that I can hold more than 4 assets hosting server?
  • pjammer
    off topic, but is that your S4??? if so, nice.
  • Asset hosts support multiple domains: config.action_controller.asset_host = "assets%d.domain.com"
blog comments powered by Disqus