Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Helpers in Rails - What's the best approach when building the html string?

I usually write helpers that way:

  def bloco_vazio (texto = "", btn = "", args={})
      titulo = content_tag :h3, "Vazio!" 
      p = content_tag :p, texto
      content_tag :div, (titulo + tag(:hr) + p + btn ), args
  end

But i commonly see people using other approaches, like:

 def flash_notice
    html = ""
    unless flash.empty?
      flash.each do |f|
        html << "<div class='alert alert-#{f[:type].to_s}'>"
        html << "<a class='close' data-dismiss='alert'>×</a>"
        html << f[:text].to_s
        html << "</div>"
      end
    end
    html
 end

or

def a_helper (some_text ="")
  %{ <h3>some title</h3>
      <p>#{some_text}</p>    
  }%
end

I used these two lasts in the past and ran into some problems then started using the content_tag and tag helpers, even that i still have to use the .html_safe method sometimes.

Is there a standard way to build helpers?

like image 638
Alexandre Abreu Avatar asked Sep 06 '12 22:09

Alexandre Abreu


People also ask

What is helper method in Rails?

What are 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 .

What are view helpers in Rails?

Rails comes with a wide variety of standard view helpers. Helpers provide a way of putting commonly used functionality into a method which can be called in the view. Helpers include functionality for rendering URLs, formatting text and numbers, building forms and much more.


2 Answers

If html is longer than 1 line, i usually put the html in a partial and call it with a custom helper method

view

<= display_my_html(@item, {html_class: "active"}) %>

helper

def display_my_html(item, opts={})
  name = item.name.upcase
  html_class = opts.key?(:html_class) ? opts[:html_class] : "normal"

  render "my_html", name: name, html_class: html_class
end

partial

<div class="<%= html_class %>">
  <span class="user">
    <%= name %>
  </span>
</div>
like image 180
emrahbasman Avatar answered Oct 05 '22 09:10

emrahbasman


If you want to build a longer "safe" html the recommended way is:

html = "".html_safe
html.safe_concat "Testing boldfaced char <b>A</b>"
html
like image 33
hsgubert Avatar answered Oct 05 '22 11:10

hsgubert