Skip to content

Instantly share code, notes, and snippets.

@aarongrando
Created July 10, 2013 16:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aarongrando/5968015 to your computer and use it in GitHub Desktop.
Save aarongrando/5968015 to your computer and use it in GitHub Desktop.
Relies on the `twitter-text` and `postgres_ext` gems. Model methods on a "Post" model with an `images` column (array of strings) and `text` column (the post's text)
class Post < ActiveRecord::Base
include Twitter::Extractor
def parse_images
images_array = Array.new
extracted_links.each do |link|
if looks_like_an_image?(link)
url = URI.parse(link)
Net::HTTP.start(url.host, url.port) do |http|
if http.head(url.request_uri)['Content-Type'].start_with? 'image'
images_array << link
end
end
end
end
self.images = images_array
end
def looks_like_an_image?(url)
if url[/(?:png|jpe?g|gif|svg)$/]
return true
else
return false
end
end
def extracted_links
extract_urls(self.text)
end
end
@aarongrando
Copy link
Author

Ah, neglected to mention that this runs as a before_create.

before_create :parse_images

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment