代码之家  ›  专栏  ›  技术社区  ›  Ben

在rails中分解这些代码的最佳方法是什么

  •  0
  • Ben  · 技术社区  · 7 年前

      <% @pois.each_with_index do |poi, i| %>
            <div class="card-item">
              <% if poi.poitable.sleep_images.blank? %>
                <div class="card-sleep-thumb" style="background-image: url(<%= cl_image_path("comingsoon.jpg", :width=>600, :crop=>"scale") %>);">
              <% else %>
                <div class="card-sleep-thumb" style="background-image: url(<%= cl_image_path(poi.poitable.sleep_images.first.image, :width=>600, :crop=>"scale") %>);">
              <% end %>
    

    第二种方式,我尝试另一种方式,像这样思考:

    <div class="card-sleep-thumb" style="background-image: url(<%= if poi.poitable.sleep_images.blank? ? cl_image_path("comingsoon.jpg", :width=>600, :crop=>"scale" : cl_image_path(poi.poitable.sleep_images.first.image, :width=>600, :crop=>"scale") %>);" %>
    

    但是,也许有更好的方法,用我模型中的方法?

    你怎么能做同样的事?

    2 回复  |  直到 7 年前
        1
  •  2
  •   Tamer Shlash    7 年前

    用户辅助方法

    class SomeModelHelper
      def some_method_name(poi)
        if poi.poitable.sleep_images.blank?
          cl_image_path("comingsoon.jpg", :width=>600, :crop=>"scale")
        else
          cl_image_path(poi.poitable.sleep_images.first.image, :width=>600, :crop=>"scale")
        end
      end
    end
    
    
    // in the view
    
    <div class="card-sleep-thumb" style="background-image: url(<%= some_method_name(poi).html_safe %>);" %>
    

    poi 等级(例如 PoiHelper Poi )并为helper方法提供一个更具表现力的名称。

        2
  •  0
  •   user229044    7 年前

    || 运算符,它返回第一个“truthy”操作数,而不是 if / else 您当前正在使用:

    cl_image_path(poi.poitable.sleep_images.first&.image || "comingsoon.jpg")
    

    这个论点 cl_image_path 将是图像(如果存在),或者 "comingsoon.jpg"

    重构的第一步可以如下所示:

    <% @pois.each do |poi| %>
      <div class="card-item">
        <div class="card-sleep-thumb" style="background-image: url(<%= cl_image_path(poi.poitable.sleep_images.first.image || "coming_soon.jpg"), :width=>600, :crop=>"scale") %>);">
        </div>
       </div>
     <% end %>
    

    each 使用集合渲染。

    现有视图如下所示:

    <%= render @pois %>
    

    Poi ,部分应放置在 app/views/pois/_poi.html.erb ,它将包含以下内容:

    <div class="card-item">
      <div class="card-sleep-thumb" style="background-image: url(<%= cl_image_path(poi.poitable.sleep_images.first.image || "coming_soon.jpg"), :width=>600, :crop=>"scale") %>);">
      </div>
    </div>