Created
July 10, 2013 16:53
-
-
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)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Ah, neglected to mention that this runs as a before_create.