7

In my production.rb I set my asset_host to CloudFront like so:

config.action_controller.asset_host = 'http://xxxxxxxx.cloudfront.net'

Now I'm finding that in some circumstances (specifically, outputting JavaScript to be embedded into another site) I need to set the asset_host in the development environment too, the default null won't cut it. Ideally I want to set:

config.action_controller.asset_host = 'http://localhost:3000'

but this port can't be guaranteed, and I'm reluctant to hard-code it. Is there a way to set asset_host to the current domain and port?

Thanks!

superluminary
  • 47,086
  • 25
  • 151
  • 148

4 Answers4

8

You can make use of environment variables or Rails initializer parameters

config.action_controller.asset_host = ENV[ASSET_HOST].empty? ? 'http://' + Rails::Server.new.options[:Host] + ':' + Rails::Server.new.options[:Port] : ENV[ASSET_HOST]

This way if you set the environment variable you use that address otherwise it will use the default.

Oscar Mederos
  • 29,016
  • 22
  • 84
  • 124
Paulo Fidalgo
  • 21,709
  • 7
  • 99
  • 115
4

In Rails 4 we use a dynamic asset_host setting with a proc:

# in /config/environments/development.rb

Rails.application.configure do
  config.action_controller.asset_host = Proc.new { |source, request|
    # source = "/assets/brands/stockholm_logo_horizontal.png"
    # request = A full-fledged ActionDispatch::Request instance

    # sometimes request is nil and everything breaks
    scheme = request.try(:scheme).presence || "http"
    host = request.try(:host).presence || "localhost:3000"
    port = request.try(:port).presence || nil

    ["#{scheme}://#{host}", port].reject(&:blank?).join(":")
  }

  # more config
end

This code ensures that requests from localhost:3000, localhost:8080, 127.0.0.1:3000, local.dev and any other setup just work.

Epigene
  • 3,634
  • 1
  • 26
  • 31
  • Thanks, this worked for fixing an issue I had with wanting to support both HTTP and HTTPS dev environments with the same configuration. – TimP Mar 12 '21 at 08:41
3

This value is available during startup and might help:

Rails::Server.new.options[:Port]

Try adding it to the asset_host variable of your development.rb file.

Based on this answer: https://stackoverflow.com/a/13839447/1882605

Community
  • 1
  • 1
jbp
  • 81
  • 2
0

Try:

class ApplicationController < ActionController::Base
before_filter :find_asset_host

private

  def find_asset_host
    ActionController::Base.asset_host = Proc.new { |source|
        if Rails.env.development?
          "http://localhost:3000"
        else
          {}
        end
      }    
  end
Firoz Ansari
  • 2,505
  • 1
  • 23
  • 36