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

余生颓废 提交于 2019-12-01 17:23:18

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.

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.

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.

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