Last Updated: February 25, 2016
·
737
· 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 ·
OSZAR »