Ruby on Rails - using helpers inside erb css file gives undefined method

I have a css.erb file that contains the style of one of my pages. I have an assistant who pre-generates the URL of this image based on the location of this image.

When I call a helper function from the view, an exit is expected (a string containing the image URL). However, calling it in the css.erb file gives me an undefined method error, although I copy and paste the same function into my css file.

As if the helper is not included in the css file and is ignored.

+4
source share
1 answer

Helpers are not available by default for .css file templates. They are designed to help only in construction. However, you can try the workaround mentioned here with an initializer:

 Rails.application.assets.context_class.instance_eval do include YourHelperModule end 

Alternatively, if you only need this for one or more files, you can use the solution mentioned here by adding this code at the beginning of .css.erb:

 <% environment.context_class.instance_eval { include YourHelperModule } %> 
+7
source

All Articles