Last Updated: February 25, 2016
·
702
· dwayne

A clean way to include a JavaScript library in a Rails layout when a Protocol-relative URL won't work

While building out an example realtime chat application with Pusher and Ruby on Rails I figured out a really neat way to keep my view clean when including the Pusher JavaScript client library.

Since the library is hosted via HTTP and HTTPS and both domain names are different I couldn't just use a protocol-relative URL to solve the problem.

Here's the solution I came up with:

# app/helpers/application_helper.rb

module ApplicationHelper

  def pusher_include_tag(version)
    domain = if request.ssl?
               'https://d3dy5gmtp8yhk7.cloudfront.net'
             else
               'http://js.pusher.com'
             end

    javascript_include_tag "#{domain}/#{version}/pusher.min.js"
  end
end

And this is how you'd use it:

<%= pusher_include_tag '2.2' %>
<%= javascript_include_tag 'application' %>

1 Response
Add your response

A cleaner way is to put all these in AssetHelper module, then include it in ApplicationHelper

over 1 year ago ·