Rails: Refactoring code for DRY method
I have some code in which I loop through pieces of data and I am having to write the same code more than once, and I am wanting to "DRY it up".
Here is some of the code:
<%= raw @artist["albums"]["Albums"].uniq_by{ |a| a["Genre"] }.collect { |album| link_to album["Genre"], genre_path(CG开发者_如何转开发I::escape(album["Genre"])) unless album["Artist"]["Name"] != @term }.join(" ") %>
The piece that I am having to duplicate multiple times is the end unless album["Artist"]["Name"] != @term
is there anyway to filter an array better than having to write this unless statement everytime?
hope that makes sense
I was able to shorten the code by doing removing the uniq_by
<%= raw @artist["albums"]["Albums"].collect { |album| link_to album["Genre"], genre_path(CGI::escape(album["Genre"])) unless album["Artist"]["Name"] != @term }.uniq.join(" ") %>
It looks like you are emulating a GROUP BY query in your view. In particular your @term
clause looks like a WHERE
condition or a join constraint.
If you have an Album model around, I'd add one or more named scopes representing parts of the query, and then just chain those together in your view (with a collect
at the end to format link tags.)
精彩评论