Class: MechanizeContent::Image

Inherits:
Object
  • Object
show all
Defined in:
lib/mechanize_content/image.rb

Constant Summary collapse

MIN_WIDTH =
64
MIN_HEIGHT =
64
AD_WIDTH =
728
AD_HEIGHT =
90

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(image, base_url) ⇒ Image

Returns a new instance of Image.



14
15
16
17
18
19
# File 'lib/mechanize_content/image.rb', line 14

def initialize(image, base_url)
  @src      = URI.escape(image["src"])
  @width    = image["width"].to_i
  @height   = image["height"].to_i
  @base_url = base_url
end

Class Method Details

.best_image(images, base_url) ⇒ Object



8
9
10
11
12
# File 'lib/mechanize_content/image.rb', line 8

def self.best_image(images, base_url)
  imgs = images.map{|i| Image.new(i, base_url)}
  top_image = imgs.select{|i| i.interesting_css?}.first || imgs.select{|i| i.interesting_file?}.first
  top_image.absolute_url if top_image
end

Instance Method Details

#absolute_urlObject



57
58
59
# File 'lib/mechanize_content/image.rb', line 57

def absolute_url
  URI.parse(@src).relative? ? (URI.parse(@base_url.to_s)+@src).to_s : @src
end

#advertising?(width, height) ⇒ Boolean

Returns:

  • (Boolean)


45
46
47
# File 'lib/mechanize_content/image.rb', line 45

def advertising?(width, height)
  @src.include?("banner") || @src.include?(".gif") || ((width == AD_WIDTH) && (height == AD_HEIGHT))
end

#allows_hotlinking?Boolean

Returns:

  • (Boolean)


36
37
38
39
40
41
42
43
# File 'lib/mechanize_content/image.rb', line 36

def allows_hotlinking?
  begin
    open(absolute_url, "Referer" => "http://splitstate.com")
  rescue OpenURI::HTTPError, SocketError
    return false
  end
  true
end

#big_enough?(width, height) ⇒ Boolean

Returns:

  • (Boolean)


53
54
55
# File 'lib/mechanize_content/image.rb', line 53

def big_enough?(width, height)
  width > MIN_WIDTH && height > MIN_HEIGHT
end

#interesting_css?Boolean

Returns:

  • (Boolean)


21
22
23
# File 'lib/mechanize_content/image.rb', line 21

def interesting_css?
  valid_image?(@width, @height)
end

#interesting_file?Boolean

Returns:

  • (Boolean)


25
26
27
28
29
30
# File 'lib/mechanize_content/image.rb', line 25

def interesting_file?
  open(absolute_url, "rb") do |fh|
    is = ImageSize.new(fh.read)
    return valid_image?(is.width, is.height)
  end
end

#not_advertising?(width, height) ⇒ Boolean

Returns:

  • (Boolean)


49
50
51
# File 'lib/mechanize_content/image.rb', line 49

def not_advertising?(width, height)
  !advertising?(width, height)
end

#valid_image?(width, height) ⇒ Boolean

Returns:

  • (Boolean)


32
33
34
# File 'lib/mechanize_content/image.rb', line 32

def valid_image?(width, height)
  big_enough?(width, height) && not_advertising?(width, height) && allows_hotlinking?
end