Created
January 19, 2015 18:08
-
-
Save alduethadyn/95781f21694d704ab80a to your computer and use it in GitHub Desktop.
Ruby example of deriving the best high-res product image for a Best Buy product
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Product < ActiveRecord::Base | |
attr_accessible :data, :sku | |
serialize :data, JSON | |
def data=(data) | |
write_attribute :data, data | |
return unless data? | |
self.primary_high_res_url = high_res | |
end | |
def high_res(*search) | |
return nil unless data.present? | |
search = [ 'largeFrontImage', 'largeImage', 'angleImage', 'image' ] unless search.present? | |
search.map do | name | | |
self.class.high_res data[name] | |
end.flatten.to_set.find do | url | | |
url.present? and self.class.found? url | |
end | |
end | |
def self.high_res(url) | |
return [] unless url.present? | |
return [] if url.ends_with? '.gif' or url.include? 'default_hardlines' | |
url = url.gsub(/.\.jpg/, 'a.jpg') | |
url =~ /\d+_.*_/ ? [ url.gsub(/(\d+)_.*_/, '\1_500x500_'), url.gsub(/(\d+)_.*_/, '\1_') ] : [ url ] | |
end | |
def self.found?(url) | |
begin | |
Faraday.new(url: url) { |faraday| faraday.adapter :net_http } .head.status == 200 | |
rescue Faraday::Error::TimeoutError => e | |
logger.error "Timed out checking for high_res image URL" | |
false | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment