ruby-on-railsruby-on-rails-4assetssprocketsrails-sprockets

How to add a rails asset dependency to an environment variable with sprockets?


I made the following js.erb:

#= require cable

this.App = {};
App.cable = Cable.createConsumer('<%= Rails.application.config.web_socket_server_url %>');

I would like sprockets to regenerate the asset when web_socket_server_url is updated.

I tried to use depend_on, but it only works for files. I also tried to add a config block in an initializer (which I expected reloading all assets when changed, instead of just the one concerned):

Sprockets.register_dependency_resolver 'web-socket-server-url' do
  ::Rails.application.config.web_socket_server_url
end

config.assets.configure do |env|
  env.depend_on 'web-socket-server-url'
end

I got the idea after seeing this commit of sprocket-rails https://github.com/rails/sprockets-rails/commit/9a61447e1c34ed6d35c358935bcae4522b60b48d

But this did not work as I would have expected.

Ideally, I would have hoped to be able to register the dependency resolver in my initializer, and then adding //= depend_on 'web-socket-server-url' in my asset, so only the asset would be reloaded.

As a workaround, I might add the config in the HTML markup, and get in in the javascript without using ERB, but it does not feel as good.

How could I make this work with sprockets ?


Solution

  • The current API for that is the one that you already used.

    Sprockets.register_dependency_resolver 'web-socket-server-url' do
      ::Rails.application.config.web_socket_server_url.to_s
    end
    
    config.assets.configure do |env|
      env.depend_on 'web-socket-server-url'
    end
    

    That would invalidate all the cache when the config is changed an not the cache for that file as you pointed.