luckyframework / avram

A Crystal database wrapper for reading, writing, and migrating Postgres databases.
https://luckyframework.github.io/avram/
MIT License
165 stars 64 forks source link

ActiveStorage alternative? #156

Open watzon opened 5 years ago

watzon commented 5 years ago

It would be very cool if Avram could have, either built in or as a separate shard, a good alternative to ActiveStorage. I did a little playing around and thought this would make a good API for it:

config/storage.cr

require "avram/storage/local"
require "avram/storage/s3"

# Here is where you configure how Avram stores files
Avram::Storage.configure do |storage|
  # Store files on a local hard disk
  disk_adapter = Avram::Storage::DiskAdapter.new(root: "/path/to/root")\
  storage.attach_adapter(:local, disk_adapter)

  # Store files remotely using Amazon S3
  s3_adapter = Avram::Storage::S3Adapter.new(
    access_key_id: "",
    secret_key: "",
    region: "",
    bucket: ""
  )
  storage.attach_adapter(:s3, s3_adapter)

  # Set the default adapater based on the environment.
  if Lucky::Env.production?
    storage.set_default_adapter(:s3)
  else
    storage.set_default_adapter(:local)
  end
end

src/models/user.cr

class User < BaseModel
  include Avram::Attachable
  include Authentic::PasswordAuthenticatable

  table :users do
    column email : String
    column encrypted_password : String

    # One-to-one attachment
    has_one_attached :avatar

    # Set an adapter explicitly
    has_one_attached :avatar, adapter: :s3

    # One-to-many attachment
    has_many_attached :avatars
  end
end

As for how to implement it we could probably do something similar to what ActiveStorage does on the back end and just create a polymorphic join table called avram_attachments or something that references the name of the class and the path the file is stored at (relative to the adapter). The module Avram::Attachable could keep track of the classes that contain attachments.

alexanderadam commented 4 years ago

For others stumbling about this: Chris also opened a corresponding issue for Avram support at shrine.cr.