Skip to content

Instantly share code, notes, and snippets.

@timriley
Created May 5, 2010 03:57
Show Gist options
  • Save timriley/390364 to your computer and use it in GitHub Desktop.
Save timriley/390364 to your computer and use it in GitHub Desktop.
Handy little class for attaching arbitrary media files

Handy little class for attaching arbitrary media files (images, audio, video, etc.) to events in a timeline application. It does a couple of nifty things for supporting the varying media types:

The before_post_process method ensures we attempt to generate thumbnails only for images.

The named scopes along with the set_item_type callback gives us a way to pull out media items of a certain type, without having to go down the often more-trouble-than-it's-worth STI path.

class MediaItem < ActiveRecord::Base
belongs_to :milestone
has_attached_file :item, :styles => {:thumb => '22x22#', :medium => '300'}
before_save :set_item_type
before_post_process :is_image?
validates_presence_of :title
validates_attachment_presence :item
named_scope :images, :conditions => {:item_type => 'image'}
named_scope :audio, :conditions => {:item_type => 'audio'}
named_scope :video, :conditions => {:item_type => 'video'}
named_scope :other, :conditions => ['item_type NOT IN (?)', %w{image audio video}]
protected
def is_image?
self.item_content_type =~ /^image/
end
def set_item_type
self.item_type = self.item_content_type.split('/').first
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment