Kurisu

Kurisu

How can I use unique filename generator function with arc_ecto?

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 ?

First 7 of 7 Posts! Switch mode

Kurisu

Kurisu

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

@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…

Where Next?

Trending in Questions Top

jonnycharles
I’m in search of an Elixir library that offers PDF generation capabilities similar to Ruby’s Prawn. While there have been discussions abo...
New
spammy
I’m looking to build a personal workflow to quickly deploy web applications written in elixir/phoenix, for local consumption (ie not on t...
New
silverdr
Using Phoenix.LiveView.TagEngine as an EEx.Engine is deprecated! To compile HEEx, use Phoenix.LiveView.TagEngine.compile/2 instead. Sta...
New
saveman71
Hello ! We want new/edit form pages to POST/PUT to their own URL rather than the resources REST defaults (post /things, put /things/:id)...
New
dli
Before I dive in myself, did anyone successfully sprinkle Hologram into their existing LiveView app? Looking for hints regarding: Addi...
New
bottlenecked
Hi all, I wanted to ask how the community is dealing with post-release steps. Today we have Ecto migrations, which make sure that the db...
New
michallepicki
I am using Oban and occasionally, shortly after a deployment, a handful of jobs can fail because of dependency on other parts of the syst...
New

Other Trending Topics Top

JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
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
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
ausimian
Emily is an Elixir library that runs Nx computations on Apple’s MLX. Install it as the default Nx backend and Nx, defn, Axon, Nx.Serving,...
New
type1fool
I just stumbled on a newly redesigned elixir-lang.org. :tada: It looks like @Software_Mansion did the work, and I think it is generally a...
New
akoutmos
@hugobarauna and I (Alex Koutmos) have been hard at work on writing a book on Nerves that takes you from simply blinking LEDs to building...
New

We're in Beta

About us Mission Statement