Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to set set config.action_controller.asset_host in development

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!

like image 735
superluminary Avatar asked May 09 '13 17:05

superluminary


2 Answers

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.

like image 141
Paulo Fidalgo Avatar answered Nov 15 '22 01:11

Paulo Fidalgo


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.

like image 4
Epigene Avatar answered Nov 15 '22 01:11

Epigene