Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a css.erb file which contains the styling of one of my pages. I have a helper which preformats a URL of a given image based on the location of that image.

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

It's as if the helper is not included in the css file and is ignored.

like image 245
Stefan Dunn Avatar asked Feb 19 '23 09:02

Stefan Dunn


1 Answers

Helpers are not available by default to templated .css files. They are intended to help in view construction only. However, you can try the workaround mentioned here using an initializer:

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

Alternatively, if you only need this for one or a few files, you can use the solution mentioned here, by adding this code to the top of the .css.erb file:

<% environment.context_class.instance_eval { include YourHelperModule } %>
like image 199
PinnyM Avatar answered Feb 27 '23 10:02

PinnyM