Method: BugGuide::Photo.search
- Defined in:
- lib/bugguide/photo.rb
.search(options = {}) ⇒ Object
Search for photos. This method depends on BugGuide’s Advanced Search functionality, which will bail if your search returns too much results, so this will throw an exception in that case that you should be prepared to deal with.
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 |
# File 'lib/bugguide/photo.rb', line 36 def self.search( = {}) raise BugGuide::NoParametersException if .blank? url = "http://bugguide.net/adv_search/bgsearch.php?" .stringify_keys! headers = [:headers] || {} params = [] %w(user taxon description county city_location adult immature male female representative).each do |param| next if [param] != false && [param].blank? params << if [param] == true || [param] == false "#{param}=#{[param] ? 1 : 0}" else "#{param}=#{[param]}" end end states = [['state'], ['location']].flatten.compact.uniq params << states.map{|s| "location[]=#{s}"} unless states.blank? params << [['month']].flatten.map{|s| "month[]=#{s}"} unless ['month'].blank? url += URI.escape( params.join('&') ) photos = [] # puts "fetching #{url}" open(url, headers) do |response| html = Nokogiri::HTML(response.read.encode('UTF-8')) if html.to_s =~ /Too many results \(\d+\)/ raise BugGuide::TooManyResultsException end names = [] html.css('body > table tr').each do |tr| next if tr.css('th').size > 0 photos << BugGuide::Photo.new( thumbnail_url: tr.css('img')[0][:src], id: tr.children[1].text.to_i, url: tr.children[1].css('a')[0][:href], title: tr.children[2].text, date: tr.children[3].text, state: tr.children[4].text, county: tr.children[5].text, city_location: tr.children[6].text, taxon: BugGuide::Taxon.new( name: tr.children[7].text, id: tr.children[7].css('a')[0][:href].to_s[/\d+$/, 0], url: tr.children[7].css('a')[0][:href] ) ) end end photos end |