Module: Wallzilla::Fetcher
Constant Summary collapse
- WRONG_API_KEY =
"Your Flicker API key "
Instance Method Summary collapse
- #download_photo(url) ⇒ Object
-
#fetch(keyword) ⇒ Object
Downoads image to tempfile for the given keyword returns: file handler if image found and downloaded nil if no image found.
- #search_image(keyword) ⇒ Object
Instance Method Details
#download_photo(url) ⇒ Object
40 41 42 43 44 45 46 47 48 49 50 |
# File 'lib/wallzilla/fetcher.rb', line 40 def download_photo(url) uri = URI.parse(url) Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == "https") do |http| resp = http.get(uri.path) file = Tempfile.new(["flickr", ".jpg"], encoding: "binary") file.binmode file.write(resp.body) file.flush file end end |
#fetch(keyword) ⇒ Object
Downoads image to tempfile for the given keyword returns:
file handler if image found and downloaded
nil if no image found
15 16 17 18 19 20 21 |
# File 'lib/wallzilla/fetcher.rb', line 15 def fetch(keyword) if image = search_image(keyword) download_photo(image) else nil end end |
#search_image(keyword) ⇒ Object
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
# File 'lib/wallzilla/fetcher.rb', line 23 def search_image(keyword) url = flickr_search_url(keyword) uri = URI.parse(url) response = Net::HTTP.get_response(uri) result = JSON.parse(response.body) if (100...117).cover?(result["code"]) fail(result["message"]) end photos = result["photos"]["photo"] return nil if photos.empty? photos.first[photo_size_code] end |