Skip to content

Instantly share code, notes, and snippets.

@radzserg
Created October 10, 2016 13:00
Show Gist options
  • Select an option

  • Save radzserg/b7736db6e429488abd2774fe0c8cea76 to your computer and use it in GitHub Desktop.

Select an option

Save radzserg/b7736db6e429488abd2774fe0c8cea76 to your computer and use it in GitHub Desktop.
defmodule App.ModelHelpers.HasImageHelper do
alias App.Repo
alias App.Image
import Ecto.Changeset, only: [cast: 3]
defmacro __using__(config) do
quote do
@conf unquote(config)
def get_image_url(model, field, options \\ %{}) do
field = if is_bitstring(field), do: String.to_atom(field), else: field
image_id = Map.get(model, field)
unless is_nil(image_id) do
image = Repo.get!(Image, image_id)
width = options[:width]
height = options[:height]
url = if width || height do
{:ok, image} = Image.resized_image(image, width, height)
Image.url(image)
else
Image.url(image)
end
url
else
get_default_image(@conf[:default_image])
end
end
def has_image?(model, field) do
!is_nil(model.field)
end
#defp get_default_image(default_image) when is_function(default_image), do: default_image()
defp get_default_image(default_image), do: default_image
def save_uploaded_image(model, file, attr \\ :image_id) do
type = to_string(__MODULE__)
type = String.split(type, ".")
|> List.last
|> Macro.underscore
{:ok, image} = Image.create_from_file(file.path, type, file.filename)
params = %{}
params = Map.put(params, attr, image.id)
changeset = cast(model, params, [to_string(attr)])
user = Repo.update!(changeset)
user
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment