繁体   English   中英

如何制作此 Ruby 代码的性能友好版本?

[英]How can do a performance friendly version of this Ruby code?

大家好,我是 RoR 和 ruby​​ 的新手。

在这个项目中,我目前正在展示 4 张以前由用户上传的车辆图像。

在我的类“Vehicle”中,我有一个单例方法- 返回一个带有车辆对象附加图像的 url 的数组 -我称之为Vehicle.vehicle_images(@vehicle.id) 我想让这个方法看起来更高效,更少硬编码。

我的车辆等级:

class Vehicle < ApplicationRecord
  has_many :vehicles_attachment, dependent: :destroy
  has_many :vehicles_attachment_imagem, -> { where({ type_attachment: 'imagem' }) }, class_name: 'VehiclesAttachment', dependent: :destroy

   def self.vehicle_images(vehicle_id)
     if vehicle_id
       images = VehiclesAttachment.where({ vehicle_id: vehicle_id, type_attachment: :imagem })
       urls = []
       if !images.nil? && !images.empty?
         count = 0
         images.each do |img|
           urls << if img.attachment.file?
                     "https:#{img.attachment.url(:regular)}"
                   else
                     4.times do
urls << ActionController::Base.helpers.image_url('viatura.jpg', digest: false).to_s
                     end
                   end
          count += 1
         end
         if count < 4
           (4 - count).times do
             urls << ActionController::Base.helpers.image_url('viatura.jpg', digest: false).to_s
           end
         end
       else
         4.times do
           urls << ActionController::Base.helpers.image_url('viatura.jpg', digest: false).to_s
         end
       end
     else
       4.times do
         urls << ActionController::Base.helpers.image_url('viatura.jpg', digest: false).to_s
       end
     end
     urls
   end
end

你能帮助我吗?

作为第一步,它可以简化为:

def self.vehicle_images(vehicle_id)
  blank_image_url = ActionController::Base.helpers.image_url('viatura.jpg', digest: false).to_s

  urls = []

  if vehicle_id
    VehiclesAttachment.where(vehicle_id: vehicle_id, type_attachment: :imagem).each do |image|
      urls << img.attachment.file? ? "https:#{img.attachment.url(:regular)}" : blank_image_url
    end
  end

  urls << blank_image_url while urls.size < 4

  urls
end

但这只是第一步。 接下来的步骤可能是:

  • 确定您是否必须处理空白的vehicle_id 如果不是,那么车辆上的实例方法将比类方法更好。 并且您将能够使用定义的关联而不是类上的where
  • 我会调查是否真的有可能您有时只返回一些图像并且真的必须在它们之间填充虚拟图像。 或者,如果少于 4 个,则只在最后填充虚拟图像就足够了。这将进一步简化方法。
  • 我想知道您是否有时需要处理 4 张以上的图像? 您的代码目前无法处理。
  • 也许您可以添加变化以确保始终有四个图像?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM