Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails view helpers in helper file

I'm probably missing something obvious here but here's what I'm trying to do.

From the view, I'm calling a custom helper function

<div>
  <%=display_services%>
</div>

In the helper file with the display_services function

def display_services
  html = "<div>"
  form_for @user do |f|
   f.text_field ...
  end
 html << "</div>"
end

I find that form_for method and f.text_field output directly to HTML stream without the div wrapper that I like. What is the proper syntax to output all the HTML in display_services? Thanks in advance for your help.

like image 888
Bob Avatar asked Sep 04 '09 18:09

Bob


People also ask

Where are custom view helpers stored within a standard Rails app?

Custom helpers for your application should be located in the app/helpers directory.

What are view helpers in Rails?

A helper is a method that is (mostly) used in your Rails views to share reusable code. Rails comes with a set of built-in helper methods. One of these built-in helpers is time_ago_in_words . This method is helpful whenever you want to display time in this specific format.

Can we use helper method in controller Rails?

In Rails 5, by using the new instance level helpers method in the controller, we can access helper methods in controllers.

What is helper role in Rails?

What is a helper? Basically helpers in Rails are used to extract complex logic out of the view so that you can organize your code better.


2 Answers

IMHO, you should not have HTML hardcoded in Ruby code. Instead, prefer partials views.

module ServicesHelper
  def display_services(user)
    render :partial => "shared/display_services", :locals => {:user => user}
  end
end
like image 102
0livier Avatar answered Oct 03 '22 18:10

0livier


Just a suggestion for style, I like doing something like this:

In your view:

<% display_services %>

Please note that the = isn't needed any more. The helper then uses concat() to append something to your page and the putting-long-strings-together thing is obsolete too:

def display_services
  concat("<div>")
  form_for @user do |f|
    f.text_field ...
  end
  concat("</div>")
end

Is it nessaccary to put the <div> tag into the helper. If you need a helper for embedding something into a block you could use some yield-magic as well:

def block_helper
  concat("<div>")
  yield
  concat("</div>")
end

And use it like this in your view - of course with helpers too:

<% block_helper do %>
  cool block<br/>
  <% display_services %>
<% end %>
like image 40
xijo Avatar answered Oct 03 '22 18:10

xijo