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?
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
concatin 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
and in your view you can just write
Hope this helps.