Kurisu

Kurisu

I’ve already created my own function to generate unique string name per given directory, using a counter stored in the directory.

MyApp.File.generate_name/1.
Ex : name = MyApp.File.generate_name “uploads/user/avatars”

The generated file name doesn’t contain the file extension.
I tried to override Arc.Definition.filename function in the file generated by Arc.g avatar.
But when when I add new user with an avatar pic, file stored in disk name differs from name stored in column “avatar” of user schema. The first name (in disk) is what I expect from overrided filename function, and the second name (in database user table) is the initial uploaded pic name.

The other problem I’m facing is that each time the Arc.Definition.filename function is called the name is generated again. I try inside the function to guess when to generate a new name but it doesn’t work well. For each new user insertion it’s called twice. Here is my overriding code :

  # Override the persisted filenames:
  def filename(version, {file, _}) do
    # is it a storage request ?
    if Map.has_key?(file, :path) do
      IO.inspect file
      MyApp.File.generate_name("uploads/user/avatars/#{version}")
    else
      Path.rootname(file.file_name)
    end
  end

Could someone guide me please ?

Showing Posts 1 to 7

Kurisu

Kurisu OP

Finally I’ve found why uploaded files are treated twice. The problem was in my user model changeset. Arc_Ecto provides a changeset function “cast_attachments(changeset, params, opts)” that manages the upload stuff. So I didn’t have to add my file field to the default “cast(params, opts)” function of my model changeset. Now that I add the upload field only to Arc_Ecto cast_attachments function, things go very better.
I still don’t have a solution to persist in DB my own generated filename but I found another solution. Now I’m ussing a UUID from elixir-uuid to save the uploaded pics. I just add a uuid column to my user schema, then check for its existence in the model changeset. If it’s nil, then I set it. ^^

  def changeset(struct, params \\ %{}) do
    struct
    |> cast(params, [:name, :slug, :age, :status, :uuid])
    |> check_uuid
    |> cast_attachments(params, [:avatar])
    |> NameSlug.maybe_generate_slug
    |> validate_required([:name, :age, :status])
  end

  defp check_uuid(changeset) do
    if get_field(changeset, :uuid) == nil do
      force_change(changeset, :uuid, UUID.uuid1)
    else
      changeset
    end
  end

end
Qqwy

Qqwy

TypeCheck Core Team

I have been fiddling with getting proper filenames in arc/arc_ecto as well.

The final filename function I use right now:

defmodule MyImage do
  use Arc.Definition
  use Arc.Ecto.Definition

  # functions to create thumbnail versions
  # ...

  def filename(version, {file, scope}) do
    # quick fix to prevent https://github.com/stavro/arc/issues/174
    file_name = Path.basename(file.file_name, Path.extname(file.file_name)) 
    "#{scope.uuid}_#{version}_#{file_name}"
  end
end

My model contains a field with the type Ecto.UUID, and in my changeset function I make sure this is set before the cast_attachments call by using

def mymodel_changeset(mymodel, attrs) do
  mymodel
  |> Map.update(:uuid, Ecto.UUID.generate, fn val -> val || Ecto.UUID.generate end)
  |> cast_attachments(attrs, [:image])
  # other validations, casts, etc.
end

Main tip to give to people would be that Ecto already has UUID-generation/handling functionality built in, so using an external library is not required.

Oh, and the approach with using Ecto.Changeset.get_field and force_change is definitely cleaner :smiley: !

Kurisu

Kurisu OP

@Qqwy
Your reply is very instructive for me. I just tested Ecto.UUID and found it perfect for the job. I will drop the external library. Thanks. :smile:

For the filename function I keep it simple like this :

# Override the persisted filenames:
  def filename(version, _) do
    version
  end

I just worked on the storage_dir function to make unique path :

  # Override the storage directory:
  def storage_dir(_, {file, scope}) do
    "uploads/avatars/#{scope.uuid}"
  end

This way for each image file uploaded, we’ll have a folder named with generated uuid, containing all the versions created (thumb, original…). The point is that when I have to delete an entry in the DB, I can simply remove its uuid corresponding folder. Beside that, I found it simpler to write my own image_delete function in the custom uploader module :

#delete all versions of an avatar
  def remove(scope) do
    storage_dir(nil, {scope.avatar, scope}) |> File.rm_rf!
  end

To be honest I have to say that I was a bit confused with the delete function of arc, so I wrote my simple own. ^^

To finish I don’t know if will have any impact on DB performance but while I’m using an uuid field for arc._ecto usage, I’m still using an Ecto default primary key for the same model. I guess a proper way to do things, would be using the uuid field as primary key in the same time ?

dokicro

dokicro

I ended up doing this:

def filename(version, {file, scope}) do
  file_name = Path.basename(file.file_name, Path.extname(file.file_name))
  "#{file_name}_#{version}_#{:os.system_time}"
end

:os.system_time should be always unique if I am not wrong :slight_smile:

OvermindDL1

OvermindDL1

Not ‘always’, but close enough for ‘most’ people not to care. :slight_smile:

julismz

julismz

Just a little apport to take in mind the performance:

And if you wanna use UUID, V3 and V5 will be your friends…

— All posts loaded —

Where Next? Top

Trending in Questions Top

RSP87
I’m working on a project that simulates the bumbl example in the programming phoenix book. It acts almost like an email client. We have a...
New
RemyXRenard
I’m seeing that a list inside a Kino.DataTable will be interpreted as a charlist, even if the Kino.configure() is set to charlists: :as_l...
New
nseaSeb
Hello, I know there is an approach for handling lists that allows for optimized traversal, but I can’t recall the specific method (somet...
New
velrest
So my question is quite simple and i have found no conclusive answer on forum, google or AI. Should we use :erlang.float for Integer to ...
New
samoloth
Hi, I’ve just set up an application with ash_authentication. There is only magic link strategy for now, so there is no confirmation add o...
New
FlyingNoodle
If a change or preparation module uses Ash.Changeset.get_argument/2 or Ash.Query.get_argument/2 (or any of the other get_argument functio...
New
ryanwinchester
apply_graft/2 doesn’t rewrite an add_many sub-workflow’s deps on an add step. Grafted jobs cancel with “upstream job was deleted” Version...
New

Other Trending Topics Top

mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
marciok
Hi there! We created Gust: A task orchestrator inspired by Airflow. For those who have never heard about Aiflow, it’s a Python-based wor...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Dmk
Xamal is a deployment tool for Elixir apps that deploys native releases to bare metal servers over SSH. It’s a port of GitHub - basecamp/...
New
Damirados
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge & Solve. They are GUI (Emerge) and State management (S...
New
netoum
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews