【发布时间】:2018-09-15 21:57:57
【问题描述】:
我的 Rails 应用中有以下视图:
app/views/matches/_round.html.erb
matches.each do |match|
# some html code here
<%= predictions(@pool, match, @current_participant) %>
# more html code here
end
以及以下辅助方法:
app/helpers/match_predictions_helper.rb
def predictions(pool, match, participant)
if match.can_be_predicted_in?(pool)
random_predictions_for_match = match.random_predictions_in_pool(pool)
if random_predictions_for_match.empty?
"<h3> No predictions available yet </h3>".html_safe
else
random_predictions_for_match.each do |prediction|
tooltip_title = "undisclosed participant"
outcome_class = ""
render partial: 'match_predictions/prediction', locals: { match: match, prediction: prediction, tooltip_title: tooltip_title, outcome_class: outcome_class }
end
end
else
match.predictions_in_pool(pool, current_user).each do |prediction|
tooltip_title = prediction.participant.username
outcome_class = prediction.class_name
render partial: 'match_predictions/prediction', locals: { match: match, prediction: prediction, tooltip_title: tooltip_title, outcome_class: outcome_class }
end
end
end
所以我的意图是显示每场比赛的预测列表,但该列表会根据某些条件而变化。我可以通过在视图中包含以下逻辑来实现这一点:
app/views/matches/_round.html.erb
matches.each do |match|
<% if match.can_be_predicted_in?(@pool) %>
<% random_predictions_for_match = match.random_predictions_in_pool(@pool) %>
<% if random_predictions_for_match.empty? %>
<h3> No predictions to spy available yet </h3>
<% else %>
<% random_predictions_for_match.each do |prediction| %>
<% tooltip_title = "undisclosed participant" %>
<% outcome_class = "" %>
<%= render partial: 'match_predictions/prediction', locals: { match: match, prediction: prediction, tooltip_title: tooltip_title, outcome_class: outcome_class } %>
<% end %>
<% end %>
<% else %>
#etc, etc, the rest of the code below.
end
不过,我想将逻辑从视图中剥离出来。到目前为止,我遇到的是,当将each 循环放在帮助程序中时,在我看来,我返回了一个数组,其中包含所有循环的对象,而不是每个循环项的预期部分呈现。助手正在输出循环本身而不是其中的内容(即要渲染的部分)。奇怪的是,在我的服务器日志中,我看到每次迭代都会呈现部分内容。
我经常使用助手和部分渲染循环迭代产生的对象,但我注意到我不太了解render 和助手在尝试将循环卡在助手中时的工作方式。
任何帮助将不胜感激。
更接近解决方案,基于下面的 Taryn 建议
因此,predictions 帮助器的输出将是一个数组,因此您必须在视图中循环遍历它,所以我这样做了。
matches.each do |match|
<% predictions(@pool, match, @current_participant).each do |prediction| %>
<%= prediction %>
<% end %>
end
另外,出于同样的原因,作为字符串的第一个条件输出也应该放入results 数组中:
# more code here
if random_predictions_for_match.empty?
results << ["<h3> No predictions to spy available yet </h3>".html_safe]
else
# more code here
我仍然遇到问题,因为浏览器不会将部分呈现的内容读取为 html,所以现在我已将所有部分内容移动到另一个帮助程序,现在在调用部分内容的地方调用该帮助程序。这有效并减少了视图中的逻辑,除了额外的predictions 每个循环。
任何更多关于清洁代码的建议表示赞赏。
【问题讨论】: