2013-04-27 35 views
0

我是新來的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>&nbsp;<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 %> 

我混帳調用此方法的一部分

https://github.com/nathan-wallace/dcphotogrid-app.git

+0

'return unless imgfile && imgfile.exif &&!imgfile.exif.empty?'? – numbers1311407 2013-04-27 22:07:56

+0

這允許我發佈沒有exif數據的圖像,但在使用exif數據上傳圖像時仍然出現錯誤 – 2013-04-27 22:14:31

+0

感謝這非常接近,請參閱我的答案。 – 2013-04-27 22:21:01

回答

0

您可以檢查是否img_loc_lat是零:

<% unless @pin.img_loc_lat.nil? %> 

如果存在的img_loc_lat是一個字符串或零成爲了可能,也可以將其轉換爲字符串,並檢查它是否是空的:

<% unless @pin.img_loc_lat.to_s.empty? %> 
0

你可以重寫HTML塊作爲助手,然後把它作爲一個方法使用.try()

@instance.try(:method_name) 

如果@instance爲空,則該方法將不會被調用。