Configure dynamic assets_host in Rails 3

前端 未结 4 781
孤街浪徒
孤街浪徒 2021-01-03 07:23

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

相关标签:
4条回答
  • 2021-01-03 07:53

    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
    }
    
    0 讨论(0)
  • 2021-01-03 08:02

    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“.
    
    0 讨论(0)
  • 2021-01-03 08:03

    In config/environments/production.rb etc.

    config.action_controller.asset_host = "http://assets." << request.host
    
    0 讨论(0)
  • 2021-01-03 08:05

    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!

    0 讨论(0)
提交回复
热议问题