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 ?

Marked As Solved

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: !

Also Liked

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:

Last Post!

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?

Popular in Questions Top

rms.mrcs
Hi, I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list. ...
New
jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod – where is this set? Thanks.
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers’ Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
Lily
In templates/appointment/index.html.eex: <%= for appointment <- @appointments do %> <tr> <td><%= appoi...
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
Harrisonl
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service. Currently when I de...
New
jason.o
In the code below, if the create action is not set to accept “extra_key” as an input, it errors out with a message shown above. Is there ...
New

Other popular topics Top

electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
Darmani72
If I have a post route which an argument: post /my_post_route/:my_param1, MyController.my_post_handler How would get the post params ...
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
AstonJ
Posting this to see if we can make things easier for people to get into Neovim. If you use Neovim and have a favourite distro please let ...
New

We're in Beta

About us Mission Statement