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!
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With