Reputation: 49152
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!
Upvotes: 7
Views: 8835
Reputation: 3908
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.
Upvotes: 4
Reputation: 22296
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.
Upvotes: 8
Reputation: 2515
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
Upvotes: 0
Reputation: 81
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
Upvotes: 3