Skip to content

Cannot inject behavior into assets.context_class when precompiling assets. #307

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
bhaibel opened this issue Jan 11, 2016 · 2 comments
Closed

Comments

@bhaibel
Copy link

bhaibel commented Jan 11, 2016

I'm mixing Rails helpers into my sprockets context per the documentation here:

https://github.com/rails/sprockets/blob/master/lib/sprockets/context.rb#L6-L18

This is happening in a Rails.application.config.after_initialize block. So something like this

Rails.application.config.after_initialize do
  Rails.application.assets.context_class.class_eval do
    include RailsViewHelperStuff
  end
end

When I precompile assets in the development rails env, this works fine. However, once I start working in an env where Rails.application.config.assets.compile is false, I get a NoMethodError: undefined methodcontext_class' for nil:NilClass`.

This appears to be a side effect of #220, which stopped building Rails.application.assets when Rails.application.config.assets.compile was false. Because y'all merged #222, I'm guessing that breaking precompilation in this case was an accident rather than you intentionally deprecating the context_class injection interface.

@bhaibel
Copy link
Author

bhaibel commented Jan 11, 2016

I'm guessing this could be trivially fixed by moving the build_environment here:

https://github.com/rails/sprockets-rails/blob/master/lib/sprockets/railtie.rb#L164

outside of the if statement, but that doesn't sound like it's within the spirit of #220.

@rafaelfranca
Copy link
Member

You should not use a after_initialize block. Use a configure block that is the correct way to configure the assets pipeline:

Rails.application.config.assets.configure do |env|
  env.context_class.class_eval do
    include RailsViewHelperStuff
  end
end

wied03 added a commit to wied03/karma-opal-rspec that referenced this issue Jan 15, 2016
Based on comments @ rails/sprockets-rails#307, I might have been using this wrong. This should work on both sprockets-rails 3.0 and 2.3
Odaeus added a commit to Odaeus/polymer-rails that referenced this issue Feb 10, 2016
Turns out that `config.after_initialize` receives a special instance of
Sprockets::Environment that is immutable when in test and production
environments.

The correct way to configure Sprockets is to use
`app.config.assets.configure` with a block. As mentioned here:
rails/sprockets-rails#307 (comment)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants