Logo Questions Linux Laravel Mysql Ubuntu Git Menu

Rails asset pipeline Rails.application.assets.instance_variable_get('@environment') returns nil

I am trying to compile javascript dynamically and then adding it to the sprockets store so it is available. Everywhere I researched suggested the below code to register the javascript:

env = Rails.application.assets.is_a?(Sprockets::Index) ? Rails.application.assets.instance_variable_get('@environment') : Rails.application

Rails.application.config.assets.digests[file_name] = env[file_name].digest_path

in production, Rails.application.assets.instance_variable_get('@environment') always returns nil, is there something I am doing wrong? or should I be adding something else?

like image 654
user1375640 Avatar asked Mar 23 '23 09:03


1 Answers

Rails.application.assets itself is an instance of Sprockets::Environment @environment' is a variable of assets_manifest, that belongs to Rails.application, like this:


I got similar problems with RAILS 3.2.15, but it was Rails.application.assets returns nil quiet_assets.rb:4:in': undefined method logger=' for nil:NilClass (NoMethodError)

the issued line was Rails.application.assets.logger = Logger.new('logger.log')

I back to Rails console, and find Rails.application.assets just returned nil.

I fix this issue by this step:

  1. include two gem in your Gemfile in case you don't have it. gem 'sprockets' gem 'sprockets-rails'

  2. find the file cause the issue , and initial your assets object. you can also put that in application.rb , in my case I put it in config/initializers/quiet_assets.rb , before I refer to logger.

    add this line:

    Rails.application.assets = Sprockets::Environment.new

    before this issued line:

    Rails.application.assets.logger = Logger.new('logger.log')

  3. in application.rb , remember have activate assets pipeline . config.assets.enabled = true

  4. for production you may need to set config.assets.compile = true

hope this helps somehow

like image 194
twindai Avatar answered Apr 24 '23 17:04