我是ruby on rails的新手,还不能真正编写方法......
上传不包含exif数据的图片时出错。
我需要这个方法来同时允许imgfile和imgfile.nil。如果imfile.nil?
,我将如何定义默认值或忽略此代码?# Image geolocation
def get_image_loc
imgfile = EXIFR::JPEG.new(image.queued_for_write[:original].path)
return unless imgfile
lat = imgfile.exif[0].gps_latitude[0].to_f + (imgfile.exif[0].gps_latitude[1].to_f / 60) + (imgfile.exif[0].gps_latitude[2].to_f / 3600)
lng = imgfile.exif[0].gps_longitude[0].to_f + (imgfile.exif[0].gps_longitude[1].to_f / 60) + (imgfile.exif[0].gps_longitude[2].to_f / 3600)
lat = lat * -1 if imgfile.exif[0].gps_latitude_ref == "S" # (N is +, S is -)
lng = lng * -1 if imgfile.exif[0].gps_longitude_ref == "W" # (W is -, E is +)
self.img_loc_lat = lat # imgfile.gps_latitude
self.img_loc_lng = lng # imgfile.gps_longitude
end
end
这是在我的show.erb文件中调用此方法的部分
<% unless @pin.img_loc_lat.blank?
# bespoke code to load a map if the location information is available
# Google Static Maps for now
# Look to upgrade to Google Maps API 3 - there seem to be a few gems available for it
%>
<p> <br />
<img src="http://maps.googleapis.com/maps/api/staticmap?center=<%= @pin.img_loc_lat %>,<%= @pin.img_loc_lng %>&zoom=13&size=600x300&maptype=roadmap&markers=color:green%7Clabel:P%7C<%= @pin.img_loc_lat %>,<%= @pin.img_loc_lng %>&sensor=false">
</p>
<% end %>
我的git
答案 0 :(得分:0)
您可以检查img_loc_lat是否为nil:
<% unless @pin.img_loc_lat.nil? %>
如果img_loc_lat
可能是字符串或nil,您也可以将其转换为字符串并检查它是否为空:
<% unless @pin.img_loc_lat.to_s.empty? %>
答案 1 :(得分:0)
您可以将html块重写为帮助程序,然后将其作为方法调用.try()
@instance.try(:method_name)
如果@instance为空,则不会调用该方法。