Create the full url for javascript in rails (similar to javascript_path, but url)

How can I create an Absolute link in a javascript file.

I assume there should be something like below (which unfortunately does not seem to be available):

javascript_url 'main' # -> 'http://localhost:3000/javascripts/main.js' 

instead:

 javascript_path 'main' # -> '/javascripts/main.js' 

I need an absolute URL because this javascript file will be used in the bookmarket.
Also, I need the same for the css file.

Thank,
Dmitry.

+6
url ruby ruby-on-rails helpers
Dec 21 '09 at 12:52
source share
3 answers

Absolute URLs for javascript and css files are now available in Rails 4 in ActionView :: Helpers :: AssetUrlHelper via Asset Pipeline. In your case, that is javascript_url and its alias url_to_javascript and the corresponding methods for style sheets.

And the result is exactly the same as you mentioned in your question:

 javascript_url 'main' # -> 'http://localhost:3000/javascripts/main.js' 

Although the question was asked many years ago, I hope that this will help people who will answer the same question in the future.

+5
Mar 31 '15 at 19:29
source share

I wrote this little helper to do this:

 def absolute_javascript_url(source) uri = URI.parse(root_url) uri.merge(javascript_path(source)) end 

The key part of URI.merge , which will automatically and correctly merge relative javascript_path with root_url.

+2
Sep 18 '10 at 8:01
source share

Perhaps you could just use javascript_path in combination with root_url ?

For example:

 root_url + javascript_path("main") 

root_url automatically generated by your root route.

You can also configure Rails helpers to use a specific "base path" by setting ActionController::Base.asset_host to the environment configuration file. Read the documentation for more details.

+1
Dec 21 '09 at 12:58
source share



All Articles