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' %>
Written by Dwayne Crooks
Related protips
1 Response
A cleaner way is to put all these in AssetHelper module, then include it in ApplicationHelper
over 1 year ago
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Ruby
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#