Skip to content

Instantly share code, notes, and snippets.

@mehlah
Created February 5, 2016 10:46
Show Gist options
  • Save mehlah/9b852d24d44a0af934ad to your computer and use it in GitHub Desktop.
Save mehlah/9b852d24d44a0af934ad to your computer and use it in GitHub Desktop.
CarrierWave store the content type
begin
require 'bundler/inline'
rescue LoadError => e
$stderr.puts 'Bundler version 1.10 or later is required. Please update your Bundler'
raise e
end
gemfile(true) do
source 'https://rubygems.org'
gem 'rails'
gem 'carrierwave', github: 'carrierwaveuploader/carrierwave'
gem 'sqlite3'
end
require 'active_record'
require 'carrierwave'
require 'carrierwave/orm/activerecord'
require 'minitest/autorun'
require 'logger'
ActiveRecord::Base.establish_connection(adapter: 'sqlite3', database: ':memory:')
ActiveRecord::Base.logger = Logger.new(STDOUT)
ActiveRecord::Base.raise_in_transactional_callbacks = true
ActiveRecord::Schema.define do
create_table :posts, force: true do |t|
t.string :image
t.string :image_content_type
end
end
class ImageUploader < CarrierWave::Uploader::Base
process :save_content_type_in_model
def save_content_type_in_model
model.image_content_type = file.content_type if file.content_type
end
end
class Post < ActiveRecord::Base
mount_uploader :image, ImageUploader
end
class ContentTypeTest < Minitest::Test
def test_content_type
post = Post.new
post.image = File.open('ruby-logo.png')
post.save!
assert_equal 'image/png', post.image_content_type
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment