Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?

Store file uploads in the database

This gem allows to store carrierwave uploads in the database, eg. on platforms with ephemeral filesystems like Heroku.

Installation

# In: Gemfile
gem 'carrierwave-blob', git: "https://gist.github.com/f1dc8c75d67b92b23a55.git"

Usage

  1. Setup your uploader to use the blob storage:
# In: app/uploaders/picture_uploader.rb
storage CarrierWave::Storage::Blob
  1. Generate a migration for your model:
rails generate carrier_wave_blob_migration Idea
  1. Execute the migrations:
rake db:migrate

Created during RailsGirls Prague

class CarrierWaveBlobMigrationGenerator < Rails::Generators::NamedBase
desc "Creates a migration to update column type to text"
argument :fieldname, default: 'picture'
check_class_collision
def create_migration_file
migration_nr = ActiveRecord::Migration.next_migration_number(Time.now.to_i)
create_file "db/migrate/#{migration_nr}_update_#{name.downcase}_#{fieldname.downcase}_column.rb",
<<-CONTENT.gsub(/^\s{6}/, '')
class Update#{name.capitalize}#{fieldname.capitalize}Column < ActiveRecord::Migration
def change
change_column :#{name.tableize}, :#{fieldname}, :text, limit: nil
end
end
CONTENT
say "Don't forget to run `rake db:migrate`!", :yellow
end
end
# -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = "carrierwave-blob"
s.version = "0.0.1"
s.platform = Gem::Platform::RUBY
s.summary = "BLOB support for Carrierwave"
s.authors = [ 'Karel Minarik', 'Vojtech Hyza' ]
s.email = [ 'karmi@karmi.cz', 'vhyza@vhyza.eu' ]
s.files = `git ls-files`.split("\n")
s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
s.require_paths = ["."]
s.add_dependency "carrierwave"
end
# encoding: utf-8
module CarrierWave
module Storage
class Blob < Abstract
class Content
def initialize(content)
@content = content
end
def url(options={})
@content
end
def to_s
@content
end
end
def store!(file)
# require "pry"; binding.pry
type = uploader.file.content_type
blob = Base64.encode64(self.uploader.file.read)
uploader.model.update_columns self.uploader.mounted_as => "data:#{type};base64,#{blob}"
end
def retrieve!(identifier=nil)
Content.new uploader.model.read_attribute(self.uploader.mounted_as)
end
end
end
end
class CarrierWaveBlobRailtie < Rails::Railtie
generators do
require 'carrierwave-blob-generator'
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment