Created
December 15, 2010 19:43
-
-
Save gzigzigzeo/742492 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
# DRAFT | |
module CarrierWave::Meta | |
extend ActiveSupport::Concern | |
included do | |
before :cache, :store_original_meta | |
[:width, :height, :content_type, :size, :filename].each do |m| | |
define_method :"meta_#{m}" do |*args| | |
style = args.first | |
style ||= :original | |
meta[style][m] unless meta.blank? | |
end | |
end | |
end | |
module ClassMethods | |
def store_meta | |
process :store_meta | |
end | |
end | |
module InstanceMethods | |
def meta | |
raise "Can not read carrierwave metadata for #{mounted_as}: #{meta_column} attribute is not defined" unless has_meta_column? | |
meta = self.model[meta_column] | |
meta = unless meta.blank? | |
Marshal.load(ActiveSupport::Base64.decode64(meta)) rescue nil | |
end | |
meta || {} | |
end | |
private | |
def meta_column | |
:"#{self.mounted_as}_meta" | |
end | |
def has_meta_column? | |
self.model.has_attribute?(meta_column) | |
end | |
def save_meta(meta) | |
self.model[meta_column] = ActiveSupport::Base64.encode64(Marshal.dump(meta)) | |
end | |
# This is used to determine original file name && content type, because the first call of | |
# store_meta processor recieves the sanitized file name and so on. | |
def store_original_meta(file) | |
@original ||= { | |
:filename => file.original_filename, | |
:size => file.size, | |
:content_type => file.content_type | |
} | |
end | |
def store_meta | |
if has_meta_column? | |
version_meta = { | |
:content_type => self.file.content_type, | |
:size => self.file.size | |
} | |
if self.respond_to?(:manipulate!) && self.file.content_type =~ /image/ | |
version_meta[:width], version_meta[:height] = get_dimensions | |
end | |
version_name = (self.version_name || :undefined).to_sym | |
meta = self.meta | |
meta[:original] = @original unless @original.blank? | |
meta[version_name] = version_meta | |
save_meta(meta) | |
end | |
end | |
def get_dimensions | |
width = 0 | |
height = 0 | |
manipulate! do |img| | |
if img.is_a?(::Magick::Image) | |
width = img.columns | |
height = img.rows | |
else | |
raise "Processor is not supported. Fork me and update me." | |
end | |
img | |
end | |
[width, height] | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment