Skip to content

Instantly share code, notes, and snippets.

@mehlah
Created February 5, 2016 10:46
Show Gist options
  • Select an option

  • Save mehlah/9b852d24d44a0af934ad to your computer and use it in GitHub Desktop.

Select an option

Save mehlah/9b852d24d44a0af934ad to your computer and use it in GitHub Desktop.

Revisions

  1. mehlah created this gist Feb 5, 2016.
    52 changes: 52 additions & 0 deletions carrierwave_content_type.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,52 @@
    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