Module: Charles::Images

Included in:
Document
Defined in:
lib/charles/images.rb

Instance Method Summary collapse

Instance Method Details

#calculate_image_from_node(_node) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/charles/images.rb', line 23

def calculate_image_from_node(_node)
  _imgs = _node.search('img')
  
  i=URI.parse(@options[:url])
  if !_imgs.empty? && _imgs.size < 50 #sanity check if more than 50 images...
    o=[]
    _imgs.each do |_img|
      next unless _img.attr('src')
      begin
        _u = (i + _img.attr('src')).to_s
      rescue StandardError => e
        logger.info "Error #{e}: #{i} + #{_img.attr('src')}"
        next
      end
      o << _u
    end
    return o
  end
  
  return nil
end

#calculate_imagesObject



9
10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/charles/images.rb', line 9

def calculate_images
  _node = self.content_node
  return unless _node
  #logger.info _node.pretty_inspect
  
  (_node.ancestors.size.to_f/2).round.times do
    o=self.calculate_image_from_node(_node)
    #logger.info o.pretty_inspect
    return o if o
    _node = _node.parent
  end
  
  return []
end

#filtered_imagesObject



45
46
47
# File 'lib/charles/images.rb', line 45

def filtered_images
  filtered_images_extra.collect{|image| image[:url]}
end

#filtered_images_extraObject



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/charles/images.rb', line 48

def filtered_images_extra
  _max_proportion = 2.5
  _min_area = 88*88
  _filtered_images = []
  _images = self.images.dup
  _images.each{|url|
    data = get_image(url)
    next unless data
    size = ImageSize.new(data).get_size
    if(size[0] * size[1] > _min_area &&
      size[0].to_f/size[1] < _max_proportion &&
      size[1].to_f/size[0] < _max_proportion)
      _filtered_images << {:url => url, :data => data, :width => size[0], :height => size[1]}
    end
  }
  return _filtered_images
end

#get_image(url) ⇒ Object



66
67
68
69
70
71
72
73
74
75
76
# File 'lib/charles/images.rb', line 66

def get_image(url)
  _cache_key = "get_image(#{url})"
  begin
    Charles.file_cache.fetch(_cache_key) {
      body = mechanize_agent.get(url, [], URI.parse(@options[:url])).body
      body.size < 900000 ? body : nil
    }
  rescue StandardError, Timeout::Error
    Charles.file_cache.write(_cache_key, nil, :expires_in => 1.hour)
  end
end

#imageObject



3
4
5
# File 'lib/charles/images.rb', line 3

def image
  images && images.first
end

#imagesObject



6
7
8
# File 'lib/charles/images.rb', line 6

def images
  @images ||= calculate_images
end