Module: Twimage

Defined in:
lib/twimage.rb,
lib/twimage/image.rb,
lib/twimage/version.rb

Defined Under Namespace

Classes: Image, ImageNotFound, ImageURLInvalid, ServiceURLInvalid

Constant Summary collapse

SERVICES =
[{ :name => :twitpic,
:service_match => /twitpic\.com/,
:full_url_modifier => lambda { |url| url + '/full' },
:image_css_match => 'body > img' },
              { :name => :yfrog,
:service_match => /yfrog\.com/,
:full_url_modifier => lambda { |url| url.gsub(/\.com/, '.com/z') },
:image_css_match => '#the-image img' }]
VERSION =
"0.0.12"

Class Method Summary collapse

Class Method Details

.find_service(url) ⇒ Object

figure out which service this is by matching against regexes



37
38
39
40
41
# File 'lib/twimage.rb', line 37

def self.find_service(url)
  return SERVICES.find do |service|
    url.match(service[:service_match])
  end
end

.get(url) ⇒ Object



25
26
27
28
29
30
31
32
33
# File 'lib/twimage.rb', line 25

def self.get(url)
  service_url = HTTParty.get(url).request.path.to_s                                                                 # first point HTTParty at this URL and follow any redirects to get to the final page
  service = find_service(service_url)                                                                               # check the resulting service_url for which service we're hitting
  full_res_service_url = service[:full_url_modifier] ? service[:full_url_modifier].call(service_url) : service_url  # get the full res version of the service_url
  image_url = get_image_url(service, full_res_service_url)                                                          # get the URL to the image
  image = get_image(image_url)                                                                                      # get the image itself
  
  return Image.new(:service => service[:name], :service_url => service_url, :image_url => image_url, :image => image)
end

.get_image(url) ⇒ Object

download the actual image and put into a tempfile



63
64
65
66
67
68
69
70
71
# File 'lib/twimage.rb', line 63

def self.get_image(url)
  # get the image itself
  response = HTTParty.get(url)
  if response.code == 200
    return response.body.force_encoding('utf-8')
  else
    raise ImageURLInvalid, "The image_url #{url} was not found (returned a 404)"
  end
end

.get_image_url(service, url) ⇒ Object

tear apart the HTML on the returned service page and find the source of the image



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/twimage.rb', line 45

def self.get_image_url(service, url)
  # get the content of the image page
  begin
    image_tag = Nokogiri::HTML(open(url)).css(service[:image_css_match]).first
  rescue OpenURI::HTTPError
    raise ServiceURLInvalid, "The service URL #{url} was not found (returned a 404)"
  end
  
  # get the URL to the actual image file
  if image_tag
    return image_tag['src']
  else
    raise ImageNotFound, "The service URL #{url} did not contain an identifiable image"
  end
end