Skip to content

Instantly share code, notes, and snippets.

@airhorns
Created March 9, 2010 05:35
Show Gist options
  • Save airhorns/326272 to your computer and use it in GitHub Desktop.
Save airhorns/326272 to your computer and use it in GitHub Desktop.
class Movie < ActiveRecord::Base
acts_as_taggable
has_one :download, :as => :resource, :dependent => :destroy
has_attached_file :poster, :styles => {:medium => "300x300>", :thumb => "100x100>"}
before_validation :download_remote_image, :if => :image_url_provided?
validates_associated :download
validates_presence_of :title
validates_numericality_of :year, :allow_nil => true
validates_numericality_of :imdbid, :allow_nil => true
validates_numericality_of :imdbrating, :allow_nil => true
validates_url_format_of :posterurl, :allow_nil => true
validates_inclusion_of :autogenerated, :in => [true, false]
attr_accessor :genres
private
def image_url_provided?
!self.posterurl.blank?
end
def download_remote_image
self.poster = do_download_remote_image
end
def do_download_remote_image
io = open(URI.parse(posterurl))
def io.original_filename; base_uri.path.split('/').last; end
io.original_filename.blank? ? nil : io
rescue Exception => e # catch url errors with validations instead of exceptions (Errno::ENOENT, OpenURI::HTTPError, etc...)
puts e.message
end
def self.per_page
15
end
def self.from_imdb(imdbid)
# Check to see if this movie is already in the DB. Warning: IMDBID must be known to be valid, lame.
imdbid = imdbid.id if imdbid.class == Imdb::Movie
movie = Movie.find_by_imdbid(imdbid)
if movie.nil?
movie = Movie.new_from_imdb(imdbid)
end
movie
end
def self.new_from_imdb(imdbid)
imdb = Imdb::Movie.new(imdbid)
# If a movie has been found on IMDB, parse out it's details for our own use
puts "imdb record title #{imdb.title}"
movieinfo = {
:title => imdb.title,
:year => imdb.year,
:director => imdb.director.join(", ").gsub(/[^A-Za-z0-9'", ]/, ''),
:imdbid => imdbid,
:imdbrating => imdb.rating,
:posterurl => imdb.poster,
:synopsis => imdb.plot,
:tagline => imdb.tagline,
:length => imdb.length,
:autogenerated => true
}
movie = Movie.new(movieinfo)
movie.genres = imdb.genres
movie
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment