2015-09-08 129 views
2

我正在使用gem nokogiri刪除img標記src值。 一段時間url不顯示帶擴展名的圖像文件名。Rails -nokogiri GEM:檢測URL中的MIME類型圖像

所以我試圖檢測圖像MIME類型。

爲了這個,我試過

MIME::Types.type_for("http://web.com/img/12457634").first.content_type # => "image/gif" 

,並顯示錯誤:

undefined method `content_type' for nil:NilClass (NoMethodError) 

任何解決方案?

+1

是它工作得很好。 –

+0

偉大:)很高興聽到:) –

回答

3

你得到這個錯誤:

undefined method `content_type' for nil:NilClass (NoMethodError) 

因爲MIME::Types.type_for("http://web.com/img/12457634").first對象nil有時。

爲了避免這個問題,這樣做:

MIME::Types.type_for("http://web.com/img/12457634").first.try(:content_type) 

所以,它不會崩潰您的程序,如果它是nil。如果不是nil,你得到正確的content_type

另外,檢查使用Net::HTTP圖像0​​頭,你可以寫一個方法是這樣的:

def valid_image_exists?(url) 
    url = URI.parse(url) 
    Net::HTTP.start(url.host, url.port) do |http| 
     return http.head(url.request_uri)['Content-Type'].start_with? 'image' 
    end 
end