1

我有一个返回空白的对象,这就是我想做的

@photo = [] # this is coming back blank, but it won't do the correct comparison in the ||
@sanitized_photos = PhotoPresenter.new(@photo).to_json || PhotoPresenter.default_layout.to_json

关于如何在没有强大的 if 语句的情况下使其工作的任何想法

更新 ::: 这是我的演示者的副本,效果很好。我知道我已经把收集逻辑放在这里,但它的工作方式最干净

class PhotoPresenter < Presenter

  def initialize(photo)
    @photo = photo
  end

  def to_gallery
    {
      "thumb" => @photo.image.url(:thumb),
      "image" => @photo.image.url(:large),
      "big" => @photo.image.url,
      "title" => @photo.attachable.name
    }
  end

  def self.blank_gallery
    {
        "thumb" => help.polymorphic_photo_url(nil, :large),
        "image" => help.polymorphic_photo_url(nil, :large),
        "big" => help.polymorphic_photo_url(nil, :large),
        "title" => "No photo provided"
      }
  end

  def self.as_gallery(photos)
    unless photos.blank?
      photos.collect{|object| self.new(object).to_gallery}.to_json
    else
      blank_gallery.to_json
    end
  end

end
4

1 回答 1

0
@sanitized_photos = @photo.any? ? PhotoPresenter.new(@photo).to_json : PhotoPresenter.default_layout.to_json

话虽如此,您最好将此逻辑移入 PhotoPresenter 类初始化程序

于 2012-05-09T22:07:38.220 回答