rails how to use helpers with ERB.new in service?

我的未来我决定 提交于 2020-06-17 15:26:21

问题


I have a service that uses an ERB file to render a template form.

In the form I use several helpers, but they don't seem to be available in this context.

how could I use my helpers in the rendering via ERB.new(template).result(binding) ?

this is the error I'm getting:

*** NoMethodError Exception: undefined method `image_encoded' for #<MyService>

here's the call in the service app/services/my_service.rb file:

ERB.new(template).result(binding)

here's my helper app/helpers/my_helper.rb:

module MyHelper
  def image_encoded(image_url)
    <<image stuff>>
  end
end

here's my call to the helper in the app/views/my_template/my_template.html.erb file:

<img src="<%= image_encoded(image) %>"/>

回答1:


In your service your helpers are not included by default. You can include the methods from a particular helper like this:

class MyService
  include MyHelper
end


来源:https://stackoverflow.com/questions/62211842/rails-how-to-use-helpers-with-erb-new-in-service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!