Class: Fetch::UrlFetcher

Inherits:
Object
  • Object
show all
Defined in:
lib/url-fetcher.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ UrlFetcher

Returns a new instance of UrlFetcher.



10
11
12
13
# File 'lib/url-fetcher.rb', line 10

def initialize(options={})
  @url = get_url_params(options[:url]).scheme.nil? ? "http://#{options[:url]}" : options[:url] 
  @width = options[:width].nil? ? 100 : options[:width]
end

Instance Attribute Details

#image_urlsObject (readonly)

Returns the value of attribute image_urls.



8
9
10
# File 'lib/url-fetcher.rb', line 8

def image_urls
  @image_urls
end

#titleObject (readonly)

Returns the value of attribute title.



8
9
10
# File 'lib/url-fetcher.rb', line 8

def title
  @title
end

#urlObject

Returns the value of attribute url.



7
8
9
# File 'lib/url-fetcher.rb', line 7

def url
  @url
end

#widthObject (readonly)

Returns the value of attribute width.



8
9
10
# File 'lib/url-fetcher.rb', line 8

def width
  @width
end

Instance Method Details

#findObject

def custom_error

raise(Fetch::MyCustomException, 'Your custom error message here')

end



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/url-fetcher.rb', line 19

def find
  agent = Mechanize.new
  doc = agent.get(url)

  images = doc.parser.xpath("//img/@src | //a/img/@src").map {|a|
    unless get_url_params(a.value).nil?
      image_uri = a.value
      #if fetch uri is relative, we just add host name
      if is_related_uri?(image_uri)
        image_uri = url+image_uri
      end

      #check this uri has file extension
      unless has_extention?(image_uri).empty?
        image_sizes = calculate_img_size(image_uri)
        if image_sizes
          (image_sizes[0].to_i > width) ? image_uri : nil
        else
          return nil 
        end
      end
    end
  }

  @image_urls = images.compact
  @title = doc.title
end