我有一个空白的对象,这就是我想做的事情
@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语句的情况下使其工作的任何想法
UPDATED :::这是我的演示者的副本,效果很好。我知道我已将收集逻辑放在这里,但它以最干净的方式运行
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
答案 0 :(得分:0)
@sanitized_photos = @photo.any? ? PhotoPresenter.new(@photo).to_json : PhotoPresenter.default_layout.to_json
据说你将这个逻辑转移到PhotoPresenter类初始化器
更好