Created
December 13, 2011 04:17
-
-
Save vinniefranco/1470556 to your computer and use it in GitHub Desktop.
This file contains 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
module MultiClip | |
def self.included( base ) | |
base.extend( ClassMethods ) | |
end | |
module ClassMethods | |
def has_attached_files( configs ) | |
after_initialize :gen_subdirs | |
before_save :populate_legacy_columns | |
# Setup paperclip logic for each provided config | |
configs.each do |asset, config| | |
# Initial paperclip init | |
has_attached_file asset, | |
:storage => :s3, | |
:s3_credentials => "#{Rails.root}/config/s3.yml", | |
:path => "/media/:sub_path/:class/:attachment/:style.:filename", | |
:bucket => 'FOOBUCKET' | |
# Set validations | |
validates_attachment_content_type asset, :content_type => config[:content_types] | |
# Generate random filename | |
before_post_process :randomize_file_names | |
end | |
# Store the configs for usage in callbacks | |
self.instance_variable_set( "@_multiclip", configs ) | |
end | |
end | |
private | |
# Requires sub_path column in included model | |
def gen_subdirs | |
self.sub_path ||= ran_subdirs | |
end | |
# Creates string for sub dir path eg: "01/16" | |
def ran_subdirs | |
rand_dirs = [] | |
2.times { |i| rand_dirs << rand(16).to_s.rjust(2, "0") } | |
rand_dirs.join("/") | |
end | |
# Creates a alphanumeric random hash | |
def randomize_file_names | |
# Get configs | |
self.class.instance_variable_get( "@_multiclip" ).each do |file_attr, config| | |
# Check for an upload | |
uploaded_filename = send( :"#{file_attr}_file_name" ) | |
if uploaded_filename | |
# Extract files extension | |
extension = File.extname( uploaded_filename ).downcase | |
# Rewrite filename | |
self.send( file_attr ).instance_write( :file_name, "#{SecureRandom.hex(16)}#{extension}" ) | |
end | |
end | |
end | |
# Loads up the legacy columns | |
def populate_legacy_columns | |
# Get configs | |
self.class.instance_variable_get( "@_multiclip" ).each do |file_attr, config| | |
# Make sure there is a legacy column and an upload set | |
if self.respond_to?( :"#{config[:legacy_column]}=" ) && send( :"#{file_attr}_file_name" ) | |
path = send( file_attr ).path | |
self.send( :"#{config[:legacy_column]}=", path[1..path.length] ) | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment