0

I have a Rails 5 app. Inside my FooController, I am generating some html content via:

ApplicationController.new.render_to_string("some_haml_file", locals: {foo: "bar"}, layout: false)

Inside some_haml_file.html.haml I need to perform some complicated logic, so leveraging helper methods, or something that corresponds to it, would help a lot. A .rb file of some kind to include.

Is it possible? I suspect that the question may have been answered in this SO post, but I honestly don't understand it.

JohnSmith1976
  • 536
  • 2
  • 12
  • 35
  • You can perform your complicated logic right here, in controller, and pass the result to `locals` hash – nattfodd Jan 18 '18 at 10:10
  • @nattfodd if I need to loop through multiple items and perform the same logic on them it's more convenient to have it in a helper-like setting. – JohnSmith1976 Jan 18 '18 at 10:15

1 Answers1

-1

There's a helpers folder in your application. Create a new module there that's named *anything*Helper, e.g. FooHelper. The filename should be foo_helper.rb in that case.

File's contents would be

module FooHelper
   def useful_function
   end
end

Then you can use useful_function in your HAML.

Murad Yusufov
  • 552
  • 4
  • 14
  • But how do I access it in the haml file? Please note that it is not rendered like usual, but instead with `ApplicationController.new.render_to_string`. – JohnSmith1976 Jan 19 '18 at 13:35
  • You just call it like `useful_function`, all helper modules are automatically available in templates. I would assume that it is still the case when using `render_to_string` – Murad Yusufov Jan 20 '18 at 17:03