Created
January 1, 2017 16:54
-
-
Save imranismail/89a976100182bc5d6f984a383cd4e13b to your computer and use it in GitHub Desktop.
Media Prototype
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule Blog.Attachment do | |
use Blog, :schema | |
@primary_key {:id, :binary_id, autogenerate: true} | |
@storage_path "attachments" | |
schema "attachments" do | |
field :file, :any, virtual: true | |
belongs_to :post, Post | |
timestamps() | |
end | |
def changeset(schema, params \\ %{}) do | |
schema | |
|> cast(params, [:id, :file]) | |
|> validate_required([]) | |
|> prepare_changes(&save_attachment/1) | |
end | |
def path(attachment, opts \\ []) do | |
version = Keyword.get(opts, :version, :original) | |
extension = Keyword.get(opts, :extension, ".png") | |
Path.join([@storage_path, attachment.id, "#{version}#{extension}"]) | |
end | |
defp save_attachment(changeset) do | |
uuid = Ecto.UUID.generate() | |
storage_path = Path.join([@storage_path, uuid]) | |
file = changeset.changes.file | |
Media.new(source: Media.File.new(file)) | |
|> Media.put_name(fn _, version -> version end) | |
|> Media.put_extension("png") | |
|> Media.put_storage_path(storage_path) | |
|> Media.put_type("image/png") | |
|> Media.transform(:original) | |
|> Media.validate(fn media -> media.source.extension in ~w(.png .jpg .jpeg) end) | |
|> Media.save() | |
put_change(changeset, :id, uuid) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment