重构以下代码行

时间:2016-01-05 09:06:46

标签: ruby-on-rails ruby refactoring

LoadLibrary

上述代码只能通过调用- if clean_book_intro_component(:literary_works).present? %h2 Other Books Related to #{@book.title} %p.fact-text = clean_book_intro_component(:literary_works) 编写一次吗?

clean_book_intro_component(:literary_works)

的实施
clean_book_intro_component

4 个答案:

答案 0 :(得分:1)

通常不建议在视图中分配变量。但是,在这种情况下,您可以使用通常被接受的内联赋值(只要您将使用范围保留在条件块的上下文中):

Dequeu<int> i;

另一个解决方案是记住函数内部的值。

if (intro = clean_book_intro_component(:literary_works)).present?
  %h2 Other Books Related to #{@book.title}
  %p.fact-text
    = intro

但是,只要存在对实例的引用,这将导致解释器保留数据。因此,建议仅在执行成本高昂和/或要记忆的数据有限的非常特殊情况下使用。

此外,如果帮助者接受参数,则需要一些额外的复杂性。事实上,您最终会记忆一些与可能的参数输入呈线性关系的数据。

答案 1 :(得分:1)

- clean_book_intro_component(:literary_works).tap do |cbic|
  - if cbic.present?
    %h2 Other Books Related to #{@book.title}
    %p.fact-text
      = cbic

也许我的haml错了,但想法是使用tap而不是显式保存调用的结果

答案 2 :(得分:0)

是的,只需将clean_book_intro_component(:literary_works)的结果保存在变量中,然后使用该变量而不是调用该函数。

答案 3 :(得分:0)

您可以将视图移动到局部并调用集合上的局部视图。如果集合为空,则不会呈现任何内容。类似的东西:

# a related_books partial
%h2 Other Books Related to #{@book.title}
  %p.fact-text
    = related_books


# in the calling view
= render partial: related_books, collection: [clean_book_intro_component(:literary_works)]

请参阅有关rendering collections的Rails指南。

相关问题