Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switch asset host for controller

Trying to figure out a way to change up the asset host when accessed by a certain controller.

The controller is to be strictly accessed by the https protocol, so I need the asset host to be switched over to using https. At the moment the asset host is set to a CNAME subdomain that is linked to the S3 and there is no SSL cert associated to it. What I'm trying to achieve is replace the current asset host with the https Amazon S3 URL. The only assets I'm worried about are the CSS and JS includes.

I was thinking of using a helper to strip the host from the stylesheet_link_tag and javascript_include_tag and replace them with the https Amazon S3 url. Seems a bit hackish to me though.

Or perhaps there is a way to changed asset hosts if request.ssl? is true?

I'm using Rails 3.2.x.

like image 636
Viet Avatar asked Apr 18 '12 22:04

Viet


1 Answers

Figure out a solution for my case.

Ended up using a Proc on config.action_controller.action_host in my Production environment file to handle a logic on request.ssl? and respond accordingly. Here is the code

config.action_controller.asset_host = Proc.new { |source, request = nil, *_|
  request && request.ssl? ? 'https://s3.amazonaws.com/my_bucket' : 'http://s3.my-domain.com'
}

'request' is set to nil to accomodate the cases where asset_host is called in asset files (CSS and JS if you are using the asset helper tags). Since request doesn't exist and if request isn't assigned in the args, then the error will be thrown when assets are compiled (as shown below).

This asset host cannot be computed without a request in scope. Remove the second argument to your asset_host Proc if you do not need the request, or make it optional.

The *_ is present due to a bug with option arguments in Proc http://bugs.ruby-lang.org/issues/5694

like image 161
Viet Avatar answered Nov 03 '22 03:11

Viet