Skip to content

Instantly share code, notes, and snippets.

@mtsmfm
Created September 12, 2018 08:56
Show Gist options
  • Save mtsmfm/4c9492d8368e86b83696bbece8fef3ca to your computer and use it in GitHub Desktop.
Save mtsmfm/4c9492d8368e86b83696bbece8fef3ca to your computer and use it in GitHub Desktop.
Minimal active storage example
# 1. Put this file into the root of rails repo
# 2. `bundle exec rackup -b 0.0.0.0`
# 3. `open localhost:9292`
require 'rails/all'
tmpdir = Dir.mktmpdir
Dir.chdir(tmpdir)
ENV['DATABASE_URL'] = "sqlite3://#{File.join(tmpdir, 'database.sql')}"
class TestApp < Rails::Application
secrets.secret_key_base = 'secret_key_base'
end
Rails.application.configure do
config.load_defaults 5.2
config.eager_load = true
config.active_storage.service = :local
config.logger = ActiveSupport::Logger.new(STDOUT)
config.active_storage.service_configurations = {
local: {
service: 'Disk',
root: tmpdir
}
}
config.after_initialize do |app|
ActiveRecord::Schema.define do
create_table :users, force: true do |t|
end
load File.join(Bundler.rubygems.find_name('activestorage').first.full_gem_path, 'db/migrate/20170806125915_create_active_storage_tables.rb')
CreateActiveStorageTables.new.change
end
class User < ActiveRecord::Base
has_one_attached :avatar
end
class UsersController < ActionController::Base
def index
@user = User.new
render inline: <<~ERB
<%= form_with model: @user do |f| %>
<%= f.file_field :avatar %>
<%= f.submit %>
<% end %>
<ul>
<%- User.all.each do |u| %>
<li>
<div>id: <%= u.id %></div>
<%= link_to 'download via send_data', user_path(u.id) %>
<%= link_to 'download via rails_blob_path', rails_blob_path(u.avatar, disposition: 'attachment') %>
</li>
<% end %>
</ul>
ERB
end
def create
User.create!(params.require(:user).permit(:avatar))
redirect_to users_path
end
def show
user = User.find(params[:id])
send_data user.avatar.download, disposition: 'attachment', filename: user.avatar.filename.to_s
end
end
app.routes.prepend do
root to: redirect('/users')
resources :users
end
user = User.new
user.avatar.attach(io: File.open(__FILE__), filename: %(あ"い"\\う/え'お.rb))
user.save!
end
end
Rails.application.initialize!
run Rails.application
at_exit do
FileUtils.rm_rf(tmpdir)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment