Pregunta

Please note this is not a question asking for any working solution, but a question of a what is the best practice? kind.

Throughout my views I have a lot of occurrences of the code like this (I use HAML):

= t("some.key")
%b= t("other.key.#{string}")
%i= string

As soon as it is used in many different places I decided to extract it to a helper. But I realized that I do not understand what is the cleanest way to do it.

I can think of using string concatenation (+), or string formatting ("%s %s %s" % [...]), or array join ([...].join("\n")) but all of these methods look a bit excessive for me, because I have to build some other objects (strings, arrays) or specify delimiters(" " or "\n") and bothering with html_safe instead of just declaring three string.

I thought that concat is what is supposed to work this way

def long_string(string)
  concat t("some.key")
  concat content_tag(:b, t("other.key.#{string}"))
  concat content_tag(:i, t(string)
end

... and it works, but it forces me to execute the helper instead of evaluating it, which is not idiomatic, I mean to use

%p- long_string(string)

instead of

%p= long_string(string)

Of course I can extract it to a partial, but it seems to much for a code of three lines.

That said, am I missing some clean and elegant way to concatenate three HTML-enriched lines in a helper, or concat/partial/dirty array joins are my only options?

¿Fue útil?

Solución

If it is a lot of HTML I would definitely go for extracting the partial. Nothing writes and reads HTML cleaner than HAML in my personal opinion.

If it is a bunch of string interpolation, composing a lot of values, I sometimes use helpers to clean up my view, but they would always return strings, I never use concat in my helpers, this makes my helpers better testable as well (just check if the string result is what I expect it to be).

So, for your example it would be

def long_string(str)
  result = []
  result << t("some.key")
  result << content_tag(:b, t("other.key.#{string}"))
  result << content_tag(:i, string)
  result.join(" ").html_safe
end

and in your view you can just write

%p= long_string('whatevvva')

Hope this helps.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top