Created
October 10, 2016 13:00
-
-
Save radzserg/b7736db6e429488abd2774fe0c8cea76 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 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