开发者

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

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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜