sprockets-rails
sprockets-rails copied to clipboard
Using `asset_url` within an initializer with digest
Hi,
I'm trying to use an asset_url within an initializer.
Here are some of the options I've tried:
GemRequiringAssetUrl.configure do |config|
Rails.application.config.assets.configure do |_|
config.javascript_file_url = ActionController::Base.helpers.asset_url('application.js')
end
end
GemRequiringAssetUrl.configure do |config|
config.javascript_file_url = ActionController::Base.helpers.asset_url('application.js')
end
# this works in rails console when assets compile is set to true in production.rb
# config.assets.compile = true
GemRequiringAssetUrl.configure do |config|
config.javascript_file_url = ENV.fetch('ASSET_HOST') + '/assets/' + Rails.application.assets['application.js'].digest_path
end
GemRequiringAssetUrl.configure do |config|
Rails.application.config.assets.configure do |env|
config.javascript_file_url = ENV.fetch('ASSET_HOST') + '/assets/' + env['application.js'].digest_path
end
end
None of these methods work. Both ActionController::Base.helpers.asset_url('application.js') and ENV.fetch('ASSET_HOST') + '/assets/' + Rails.application.assets['application.js'].digest_path work in production in rails console, but in initalizer, they either incorrectly return 'application.js' without the fingerprint (ActionController::Base.helpers.asset_url('application.js')) or they fail for calling digest_path on nil (Rails.application.assets['application.js'].digest_path).
I'm thinking of manually resolving the file's fingerprint, but I guess there must be a better way.
I've managed to make it working by moving the configuration code to after_initialize block in config/application.rb:
config.after_initialize do
GemRequiringAssetUrl.configuration.javascript_file_url =
ActionController::Base.helpers.asset_url('shopify_store.js')
end
Is this the proper way to do it?