Generate full url to javascript in rails (similar to javascript_path, but url)

一笑奈何 提交于 2019-12-01 16:10:51

问题


How is it possible to generate an absolute link to the javascript file.

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

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

instead of:

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

I need the absolute URL because that javascript file will be used in a bookmarklet.
Additionally I need the same for css file.

Thanks,
Dmitriy.


回答1:


Absolute URLs to javascript and css files are now available in Rails 4 in ActionView::Helpers::AssetUrlHelper module via Asset Pipeline. In your case specifically it's javascript_url and its alias url_to_javascript and corresponding methods for stylesheets.

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

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

Though the question was asked ages ago, hope it will help people seeking answer to the same question in future.




回答2:


I've written 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 being URI.merge which will automatically, and correctly merge the relative javascript_path with root_url.




回答3:


Maybe you could simply use javascript_path combined with root_url?

For example:

root_url + javascript_path("main") 

root_url is automatically generated by your root route.

You could also configure the Rails helpers to use a specific "base path" by setting ActionController::Base.asset_host in your environment's configuration file. Read more in the documentation.



来源:https://stackoverflow.com/questions/1939942/generate-full-url-to-javascript-in-rails-similar-to-javascript-path-but-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!