Created
February 23, 2011 16:24
-
-
Save reu/840653 to your computer and use it in GitHub Desktop.
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
# encoding: UTF-8 | |
require "open-uri" | |
class Video < ActiveRecord::Base | |
class YoutubeVideoValidator < ActiveModel::Validator | |
def validate(record) | |
unless record.youtube_code.include? 'youtube.com/watch?v=' | |
record.errors[:base] << "URL não é um endereço válido de um vídeo do youtube" | |
end | |
end | |
end | |
after_create :set_position | |
before_save :youtube_code_from_url, :download_video_thumb | |
has_friendly_id :name, :use_slug => true, :approximate_ascii => true | |
acts_as_list | |
has_one :image, :as => :assetable, :class_name => 'VideoImage', :dependent => :destroy | |
has_one :thumb, :as => :assetable, :class_name => 'VideoThumb', :dependent => :destroy | |
accepts_nested_attributes_for :image, :reject_if => lambda { |a| a[:attachment].blank? }, :allow_destroy => true | |
accepts_nested_attributes_for :thumb, :reject_if => lambda { |a| a[:attachment].blank? }, :allow_destroy => true | |
validates_presence_of :name | |
validates_with YoutubeVideoValidator | |
protected | |
def set_position | |
self.move_to_top | |
end | |
def youtube_code_from_url | |
unless youtube_code.blank? | |
self.youtube_code = youtube_code.split('?v=')[1] | |
self.youtube_code = youtube_code.split('&')[0] if youtube_code.include? '&' | |
end | |
end | |
def download_video_thumb | |
unless youtube_code.blank? | |
build_thumb if thumb.blank? | |
io = open("http://img.youtube.com/vi/" + youtube_code + "/2.jpg") | |
io.original_filename = "thumb.jpg" | |
thumb.attachment = io | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment