├── test ├── test_helper.exs ├── ecto_list │ └── list_item_test.exs └── ecto_list_test.exs ├── .formatter.exs ├── .gitignore ├── LICENSE ├── config └── config.exs ├── mix.exs ├── mix.lock ├── lib ├── ecto_list │ ├── context.ex │ └── list_item.ex └── ecto_list.ex ├── README.md └── guides └── tutorial.md /test/test_helper.exs: -------------------------------------------------------------------------------- 1 | ExUnit.start() 2 | -------------------------------------------------------------------------------- /.formatter.exs: -------------------------------------------------------------------------------- 1 | # Used by "mix format" 2 | [ 3 | inputs: ["{mix,.formatter}.exs", "{config,lib,test}/**/*.{ex,exs}"] 4 | ] 5 | -------------------------------------------------------------------------------- /test/ecto_list/list_item_test.exs: -------------------------------------------------------------------------------- 1 | defmodule EctoList.ListItemTest do 2 | use ExUnit.Case 3 | doctest EctoList.ListItem 4 | 5 | # List.insert_at([1, 2, 3, 4], 2, 0) 6 | # [1, 2, 0, 3, 4] 7 | 8 | # List.insert_at([1, 2, 3], 10, 0) 9 | # [1, 2, 3, 0] 10 | 11 | # List.insert_at([1, 2, 3], -1, 0) 12 | # [1, 2, 3, 0] 13 | 14 | # List.insert_at([1, 2, 3], -10, 0) 15 | # [0, 1, 2, 3] 16 | end 17 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # The directory Mix will write compiled artifacts to. 2 | /_build/ 3 | 4 | # If you run "mix test --cover", coverage assets end up here. 5 | /cover/ 6 | 7 | # The directory Mix downloads your dependencies sources to. 8 | /deps/ 9 | 10 | # Where third-party dependencies like ExDoc output generated docs. 11 | /doc/ 12 | 13 | # Ignore .fetch files in case you like to edit your project deps locally. 14 | /.fetch 15 | 16 | # If the VM crashes, it generates a dump, let's ignore it too. 17 | erl_crash.dump 18 | 19 | # Also ignore archive artifacts (built via "mix archive.build"). 20 | *.ez 21 | 22 | # Ignore package tarball (built via "mix hex.build"). 23 | ecto_list-*.tar 24 | 25 | /.elixir_ls/ 26 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | (The MIT License) 2 | 3 | Copyright (c) 2019 Sofiane Baddag & the Contributors 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 6 | 7 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 8 | 9 | THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 10 | -------------------------------------------------------------------------------- /config/config.exs: -------------------------------------------------------------------------------- 1 | # This file is responsible for configuring your application 2 | # and its dependencies with the aid of the Mix.Config module. 3 | use Mix.Config 4 | 5 | # This configuration is loaded before any dependency and is restricted 6 | # to this project. If another project depends on this project, this 7 | # file won't be loaded nor affect the parent project. For this reason, 8 | # if you want to provide default values for your application for 9 | # third-party users, it should be done in your "mix.exs" file. 10 | 11 | # You can configure your application as: 12 | # 13 | # config :ecto_list, key: :value 14 | # 15 | # and access this configuration in your application as: 16 | # 17 | # Application.get_env(:ecto_list, :key) 18 | # 19 | # You can also configure a third-party app: 20 | # 21 | # config :logger, level: :info 22 | # 23 | 24 | # It is also possible to import configuration files, relative to this 25 | # directory. For example, you can emulate configuration per environment 26 | # by uncommenting the line below and defining dev.exs, test.exs and such. 27 | # Configuration from the imported file will override the ones defined 28 | # here (which is why it is important to import them last). 29 | # 30 | # import_config "#{Mix.env()}.exs" 31 | -------------------------------------------------------------------------------- /mix.exs: -------------------------------------------------------------------------------- 1 | defmodule EctoList.MixProject do 2 | use Mix.Project 3 | 4 | def project do 5 | [ 6 | app: :ecto_list, 7 | version: "0.1.2", 8 | elixir: "~> 1.8", 9 | start_permanent: Mix.env() == :prod, 10 | deps: deps(), 11 | # Hex 12 | description: "Simple ordered model management with Ecto.", 13 | package: package(), 14 | # Docs 15 | name: "ecto_list", 16 | source_url: "https://github.com/popo63301/ecto_list", 17 | docs: [ 18 | main: "readme", 19 | extras: ["README.md": [], "guides/tutorial.md": [title: "Tutorial"]] 20 | ], 21 | groups_for_extras: [ 22 | Guides: Path.wildcard("guides/*.md") 23 | ] 24 | ] 25 | end 26 | 27 | def application do 28 | [ 29 | extra_applications: [:logger] 30 | ] 31 | end 32 | 33 | defp package do 34 | [ 35 | maintainers: ["Sofiane Baddag"], 36 | licenses: ["MIT"], 37 | links: %{github: "https://github.com/popo63301/ecto_list"}, 38 | files: ~w(lib LICENSE mix.exs README.md) 39 | ] 40 | end 41 | 42 | defp deps do 43 | [ 44 | {:ex_doc, "~> 0.20.2", only: [:dev, :doc], runtime: false}, 45 | {:mix_test_watch, "~> 0.8", only: :dev, runtime: false} 46 | ] 47 | end 48 | end 49 | -------------------------------------------------------------------------------- /mix.lock: -------------------------------------------------------------------------------- 1 | %{ 2 | "earmark": {:hex, :earmark, "1.3.2", "b840562ea3d67795ffbb5bd88940b1bed0ed9fa32834915125ea7d02e35888a5", [:mix], [], "hexpm"}, 3 | "ex_doc": {:hex, :ex_doc, "0.20.2", "1bd0dfb0304bade58beb77f20f21ee3558cc3c753743ae0ddbb0fd7ba2912331", [:mix], [{:earmark, "~> 1.3", [hex: :earmark, repo: "hexpm", optional: false]}, {:makeup_elixir, "~> 0.10", [hex: :makeup_elixir, repo: "hexpm", optional: false]}], "hexpm"}, 4 | "file_system": {:hex, :file_system, "0.2.7", "e6f7f155970975789f26e77b8b8d8ab084c59844d8ecfaf58cbda31c494d14aa", [:mix], [], "hexpm"}, 5 | "makeup": {:hex, :makeup, "0.8.0", "9cf32aea71c7fe0a4b2e9246c2c4978f9070257e5c9ce6d4a28ec450a839b55f", [:mix], [{:nimble_parsec, "~> 0.5.0", [hex: :nimble_parsec, repo: "hexpm", optional: false]}], "hexpm"}, 6 | "makeup_elixir": {:hex, :makeup_elixir, "0.13.0", "be7a477997dcac2e48a9d695ec730b2d22418292675c75aa2d34ba0909dcdeda", [:mix], [{:makeup, "~> 0.8", [hex: :makeup, repo: "hexpm", optional: false]}], "hexpm"}, 7 | "mix_test_watch": {:hex, :mix_test_watch, "0.9.0", "c72132a6071261893518fa08e121e911c9358713f62794a90c95db59042af375", [:mix], [{:file_system, "~> 0.2.1 or ~> 0.3", [hex: :file_system, repo: "hexpm", optional: false]}], "hexpm"}, 8 | "nimble_parsec": {:hex, :nimble_parsec, "0.5.0", "90e2eca3d0266e5c53f8fbe0079694740b9c91b6747f2b7e3c5d21966bba8300", [:mix], [], "hexpm"}, 9 | } 10 | -------------------------------------------------------------------------------- /lib/ecto_list/context.ex: -------------------------------------------------------------------------------- 1 | defmodule EctoList.Context do 2 | @moduledoc """ 3 | Implements conveniences to manipulate the items order list. 4 | 5 | You can implement all the functions available in this module by using this module inside of the context of 6 | the List module. 7 | (Check the guides to see how) 8 | 9 | There are two functions in this module: `sync_order_list/1` and `reset_order_list/1` 10 | 11 | They both take a `List` struct that you define when calling "use". 12 | 13 | `sync_order_list/1` : will add missing ids to the items order list of the list. 14 | 15 | `reset_order_list/1` : will set the items order as the list of ids ordered by inserted date. 16 | """ 17 | 18 | defmacro __using__(opts) do 19 | list_items_key = Keyword.get(opts, :list_items_key) 20 | items_order_key = Keyword.get(opts, :items_order_key) 21 | 22 | quote do 23 | alias unquote(Keyword.get(opts, :list)), as: List 24 | alias unquote(Keyword.get(opts, :repo)), as: Repo 25 | 26 | @list_items_key unquote(list_items_key) 27 | @items_order_key unquote(items_order_key) 28 | 29 | @doc """ 30 | Hello world. 31 | 32 | """ 33 | def sync_order_list(%List{} = list) do 34 | items = Map.get(list, @list_items_key) 35 | items_order = Map.get(list, @items_order_key) 36 | new_order = EctoList.complete_items_order(items, items_order) 37 | 38 | attrs = Map.put(%{}, @items_order_key, new_order) 39 | 40 | list 41 | |> List.changeset(attrs) 42 | |> Repo.update() 43 | end 44 | 45 | def reset_order_list(%List{} = list) do 46 | items = Map.get(list, @list_items_key) 47 | new_order = EctoList.missing_ids_list(items) 48 | 49 | attrs = Map.put(%{}, @items_order_key, new_order) 50 | 51 | list 52 | |> List.changeset(attrs) 53 | |> Repo.update() 54 | end 55 | end 56 | end 57 | end 58 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ecto_list 2 | 3 | Ecto_list is a simple library that helps you manage ordered model with Ecto. 4 | 5 | ![ecto_list](https://user-images.githubusercontent.com/29427340/61579593-79514200-ab07-11e9-8ee6-dac77b949cd2.gif) 6 | 7 | ## Description 8 | 9 | Let's take an example of an ordered model: a Serie which contains an ordered list of videos. 10 | 11 | Instead of storing the position of each video in the videos themselves, we will store the ordering in the serie and we will call `EctoList.ordered_items_list/2` to return for us the list of items properly ordered. 12 | 13 | ## Installation 14 | 15 | Read the [tutorial](guides/tutorial.md) to understand the process of installation of the library. 16 | 17 | ## Functions available 18 | 19 | In `EctoList.ListItem`, you have a set of functions to modify the ordering of your order list. The API is inspired by [`acts_as_list`](https://github.com/swanandp/acts_as_list) Ruby gem. 20 | 21 | #### Functions That Change Position and Reorder List 22 | 23 | - `EctoList.ListItem.insert_at/3` 24 | - `EctoList.ListItem.move_lower/2` will do nothing if the item is the lowest item 25 | - `EctoList.ListItem.move_higher/2` will do nothing if the item is the highest item 26 | - `EctoList.ListItem.move_to_bottom/2` 27 | - `EctoList.ListItem.move_to_top/2` 28 | - `EctoList.ListItem.remove_from_list/2` 29 | 30 | #### Methods That Return Data of the Item's List Position 31 | 32 | - `EctoList.ListItem.first?/2` 33 | - `EctoList.ListItem.last?/2` 34 | - `EctoList.ListItem.in_list?/2` 35 | - `EctoList.ListItem.not_in_list?/2` 36 | - `EctoList.ListItem.higher_item/2` 37 | - `EctoList.ListItem.higher_items/2` will return all the ids above the given list item id in the order_list 38 | - `EctoList.ListItem.lower_item/2` 39 | - `EctoList.ListItem.lower_items/2` will return all the ids below the given list item id in the order_list 40 | 41 | ## Demo 42 | 43 | See the demo [here](https://github.com/popo63301/ecto_list_demo). 44 | 45 | ## Documentation 46 | 47 | The documentation can be found here: [https://hexdocs.pm/ecto_list](https://hexdocs.pm/ecto_list). 48 | 49 | ## Contributing 50 | 51 | Feel free to open an issue or a PR if you want to add a new feature. 😁 52 | -------------------------------------------------------------------------------- /test/ecto_list_test.exs: -------------------------------------------------------------------------------- 1 | defmodule EctoListTest do 2 | use ExUnit.Case 3 | doctest EctoList 4 | 5 | @all_items [ 6 | %{id: 1, title: "Item 1", inserted_at: ~N[2019-07-16 16:03:15]}, 7 | %{id: 2, title: "Item 2", inserted_at: ~N[2019-07-16 16:04:15]}, 8 | %{id: 3, title: "Item 3", inserted_at: ~N[2019-07-16 16:05:15]}, 9 | %{id: 4, title: "Item 4", inserted_at: ~N[2019-07-16 16:06:15]}, 10 | %{id: 5, title: "Item 5", inserted_at: ~N[2019-07-16 16:07:15]} 11 | ] 12 | 13 | test "ordered_items_list/2" do 14 | assert EctoList.ordered_items_list(@all_items, [5, 3, 1]) == 15 | [ 16 | %{id: 5, title: "Item 5", inserted_at: ~N[2019-07-16 16:07:15]}, 17 | %{id: 3, title: "Item 3", inserted_at: ~N[2019-07-16 16:05:15]}, 18 | %{id: 1, title: "Item 1", inserted_at: ~N[2019-07-16 16:03:15]}, 19 | %{id: 2, title: "Item 2", inserted_at: ~N[2019-07-16 16:04:15]}, 20 | %{id: 4, title: "Item 4", inserted_at: ~N[2019-07-16 16:06:15]} 21 | ] 22 | end 23 | 24 | test "ordered_items_list/2 when item missing" do 25 | all_items_1 = [ 26 | %{id: 1, title: "Item 1", inserted_at: ~N[2019-07-16 16:03:15]}, 27 | %{id: 2, title: "Item 2", inserted_at: ~N[2019-07-16 16:04:15]}, 28 | %{id: 4, title: "Item 4", inserted_at: ~N[2019-07-16 16:06:15]}, 29 | %{id: 5, title: "Item 5", inserted_at: ~N[2019-07-16 16:07:15]} 30 | ] 31 | 32 | assert EctoList.ordered_items_list(all_items_1, [5, 3, 1]) == 33 | [ 34 | %{id: 5, title: "Item 5", inserted_at: ~N[2019-07-16 16:07:15]}, 35 | %{id: 1, title: "Item 1", inserted_at: ~N[2019-07-16 16:03:15]}, 36 | %{id: 2, title: "Item 2", inserted_at: ~N[2019-07-16 16:04:15]}, 37 | %{id: 4, title: "Item 4", inserted_at: ~N[2019-07-16 16:06:15]} 38 | ] 39 | end 40 | 41 | test "complete_items_order/2" do 42 | assert EctoList.complete_items_order(@all_items, [5, 3, 1]) == 43 | [5, 3, 1, 2, 4] 44 | end 45 | 46 | test "complete_items_order/2 when nil" do 47 | assert EctoList.complete_items_order(@all_items, nil) == 48 | [1, 2, 3, 4, 5] 49 | end 50 | 51 | test "complete_items_order/2 when items order = []" do 52 | assert EctoList.complete_items_order(@all_items, []) == 53 | [1, 2, 3, 4, 5] 54 | end 55 | 56 | test "missing_ids_list/1" do 57 | assert EctoList.missing_ids_list(@all_items) == [1, 2, 3, 4, 5] 58 | end 59 | 60 | test "missing_ids_list/2" do 61 | assert EctoList.missing_ids_list(@all_items, [5, 3, 1]) == [2, 4] 62 | end 63 | 64 | test "missing_ids_list/2 with nil" do 65 | assert EctoList.missing_ids_list(@all_items, nil) == [1, 2, 3, 4, 5] 66 | end 67 | end 68 | -------------------------------------------------------------------------------- /lib/ecto_list.ex: -------------------------------------------------------------------------------- 1 | defmodule EctoList do 2 | @moduledoc """ 3 | Implements conveniences to handle the items order of a list. 4 | """ 5 | 6 | @doc """ 7 | Returns the list of items ordered according to the items_order list. 8 | 9 | If ids are missing in items_order, the items will be ordered according to their inserted date. 10 | 11 | ## Examples 12 | 13 | all_items = [%{id: 1, title: "Item 1", inserted_at: ~N[2019-07-16 16:03:15]}, 14 | %{id: 2, title: "Item 2", inserted_at: ~N[2019-07-16 16:04:15]}, 15 | %{id: 3, title: "Item 3", inserted_at: ~N[2019-07-16 16:05:15]}, 16 | %{id: 4, title: "Item 4", inserted_at: ~N[2019-07-16 16:06:15]}, 17 | %{id: 5, title: "Item 5", inserted_at: ~N[2019-07-16 16:07:15]}] 18 | 19 | items_order = [5, 3, 1] 20 | 21 | ordered_items_list(all_items, items_order) 22 | # [%{id: 5, title: "Item 5", inserted_at: ~N[2019-07-16 16:07:15]}, 23 | # %{id: 3, title: "Item 3", inserted_at: ~N[2019-07-16 16:05:15]}, 24 | # %{id: 1, title: "Item 1", inserted_at: ~N[2019-07-16 16:03:15]}, 25 | # %{id: 2, title: "Item 2", inserted_at: ~N[2019-07-16 16:04:15]}, 26 | # %{id: 4, title: "Item 4", inserted_at: ~N[2019-07-16 16:06:15]}] 27 | 28 | """ 29 | def ordered_items_list(items, items_order \\ []) do 30 | complete_items_order = complete_items_order(items, items_order) 31 | 32 | search_function = fn x -> Enum.find(items, fn item -> item.id == x end) end 33 | 34 | Enum.map(complete_items_order, search_function) 35 | |> Enum.filter(&(!is_nil(&1))) 36 | end 37 | 38 | @doc """ 39 | Returns the list of ids composed of the current list order + all the missings ids ordered by insertion date. 40 | 41 | ## Examples 42 | 43 | all_items = [%{id: 1, title: "Item 1", inserted_at: ~N[2019-07-16 16:03:15]}, 44 | %{id: 2, title: "Item 2", inserted_at: ~N[2019-07-16 16:04:15]}, 45 | %{id: 3, title: "Item 3", inserted_at: ~N[2019-07-16 16:05:15]}, 46 | %{id: 4, title: "Item 4", inserted_at: ~N[2019-07-16 16:06:15]}, 47 | %{id: 5, title: "Item 5", inserted_at: ~N[2019-07-16 16:07:15]}] 48 | 49 | items_order = [5, 3, 1] 50 | 51 | complete_items_order(all_items, items_order) 52 | # [5, 3, 1, 2, 4] 53 | 54 | """ 55 | 56 | def complete_items_order(items, nil), do: complete_items_order(items, []) 57 | 58 | def complete_items_order(items, items_order) do 59 | missing_ids_list = missing_ids_list(items, items_order) 60 | 61 | items_order ++ missing_ids_list 62 | end 63 | 64 | @doc """ 65 | Same as `missing_ids_list/2` but returns all ids ordered by insertion date. 66 | """ 67 | def missing_ids_list(all_items), do: missing_ids_list(all_items, []) 68 | 69 | @doc """ 70 | Returns the list of missing ids ordered by insertion date. 71 | 72 | ## Examples 73 | 74 | all_items = [%{id: 1, title: "Item 1", inserted_at: ~N[2019-07-16 16:03:15]}, 75 | %{id: 2, title: "Item 2", inserted_at: ~N[2019-07-16 16:04:15]}, 76 | %{id: 3, title: "Item 3", inserted_at: ~N[2019-07-16 16:05:15]}, 77 | %{id: 4, title: "Item 4", inserted_at: ~N[2019-07-16 16:06:15]}, 78 | %{id: 5, title: "Item 5", inserted_at: ~N[2019-07-16 16:07:15]}] 79 | 80 | items_order = [5, 3, 1] 81 | 82 | missing_ids_list(all_items, items_order) 83 | # [2, 4] 84 | 85 | """ 86 | def missing_ids_list(all_items, nil), do: missing_ids_list(all_items, []) 87 | 88 | def missing_ids_list(all_items, items_order) do 89 | all_items 90 | |> sorted_items_by_inserted_date 91 | |> Enum.reduce([], fn x, acc -> 92 | if !Enum.member?(items_order ++ acc, x.id) do 93 | acc ++ [x.id] 94 | else 95 | acc 96 | end 97 | end) 98 | end 99 | 100 | defp sorted_items_by_inserted_date(items) do 101 | items 102 | |> Enum.sort(&(NaiveDateTime.compare(&1.inserted_at, &2.inserted_at) == :lt)) 103 | end 104 | end 105 | -------------------------------------------------------------------------------- /lib/ecto_list/list_item.ex: -------------------------------------------------------------------------------- 1 | defmodule EctoList.ListItem do 2 | @moduledoc """ 3 | Implements conveniences to change the items order of a list. 4 | """ 5 | 6 | @doc """ 7 | Insert an list item id in the given index of an order_list 8 | 9 | iex> EctoList.ListItem.insert_at([1, 2, 3, 4], 9, 2) 10 | [1, 9, 2, 3, 4] 11 | 12 | iex> EctoList.ListItem.insert_at([1, 2, 3], 9, 10) 13 | [1, 2, 3, 9] 14 | 15 | iex> EctoList.ListItem.insert_at([1, 2, 9, 3], 9, 2) 16 | [1, 9, 2, 3] 17 | 18 | iex> EctoList.ListItem.insert_at([1, 2, 9, 3], 9, 10) 19 | [1, 2, 3, 9] 20 | 21 | iex> EctoList.ListItem.insert_at([1, 2, 9, 3], 9, nil) 22 | [1, 2, 9, 3] 23 | """ 24 | def insert_at(order_list, _list_item, nil) do 25 | order_list 26 | end 27 | 28 | def insert_at(order_list, list_item, index) do 29 | order_list 30 | |> Enum.reject(&(&1 == list_item)) 31 | |> List.insert_at(index - 1, list_item) 32 | end 33 | 34 | @doc """ 35 | Move the list item id one rank lower in the ordering. 36 | 37 | iex> EctoList.ListItem.move_lower([1, 2, 3, 4], 3) 38 | [1, 2, 4, 3] 39 | 40 | iex> EctoList.ListItem.move_lower([1, 2, 3, 4], 1) 41 | [2, 1, 3, 4] 42 | 43 | iex> EctoList.ListItem.move_lower([1, 2, 3, 4], 4) 44 | [1, 2, 3, 4] 45 | 46 | iex> EctoList.ListItem.move_lower([1, 2, 3, 4], 5) 47 | [1, 2, 3, 4] 48 | 49 | """ 50 | def move_lower(order_list, list_item) do 51 | index = Enum.find_index(order_list, &(&1 == list_item)) 52 | insert_at(order_list, list_item, index && index + 2) 53 | end 54 | 55 | @doc """ 56 | Move the list item id one rank higher in the ordering. 57 | 58 | iex> EctoList.ListItem.move_higher([1, 2, 3, 4], 3) 59 | [1, 3, 2, 4] 60 | 61 | iex> EctoList.ListItem.move_higher([1, 2, 3, 4], 1) 62 | [1, 2, 3, 4] 63 | 64 | iex> EctoList.ListItem.move_higher([1, 2, 3, 4], 5) 65 | [1, 2, 3, 4] 66 | 67 | """ 68 | def move_higher(order_list, list_item) do 69 | index = Enum.find_index(order_list, &(&1 == list_item)) 70 | 71 | case index do 72 | nil -> 73 | order_list 74 | 75 | 0 -> 76 | order_list 77 | 78 | _ -> 79 | insert_at(order_list, list_item, index) 80 | end 81 | end 82 | 83 | @doc """ 84 | Move the list item id at the last position in the ordering. 85 | 86 | iex> EctoList.ListItem.move_to_bottom([1, 2, 3, 4], 3) 87 | [1, 2, 4, 3] 88 | 89 | iex> EctoList.ListItem.move_to_bottom([1, 2, 3, 4], 1) 90 | [2, 3, 4, 1] 91 | 92 | iex> EctoList.ListItem.move_to_bottom([1, 2, 3, 4], 4) 93 | [1, 2, 3, 4] 94 | 95 | iex> EctoList.ListItem.move_to_bottom([1, 2, 3, 4], 5) 96 | [1, 2, 3, 4, 5] 97 | 98 | """ 99 | def move_to_bottom(order_list, list_item) do 100 | length = length(order_list) 101 | 102 | case Enum.member?(order_list, list_item) do 103 | true -> insert_at(order_list, list_item, length) 104 | false -> insert_at(order_list, list_item, length + 1) 105 | end 106 | end 107 | 108 | @doc """ 109 | Move the list item id at the first position in the ordering. 110 | 111 | iex> EctoList.ListItem.move_to_top([1, 2, 3, 4], 3) 112 | [3, 1, 2, 4] 113 | 114 | iex> EctoList.ListItem.move_to_top([1, 2, 3, 4], 1) 115 | [1, 2, 3, 4] 116 | 117 | iex> EctoList.ListItem.move_to_top([1, 2, 3, 4], 5) 118 | [5, 1, 2, 3, 4] 119 | 120 | """ 121 | def move_to_top(order_list, list_item) do 122 | insert_at(order_list, list_item, 1) 123 | end 124 | 125 | @doc """ 126 | Remove the list item id in the ordering. 127 | 128 | iex> EctoList.ListItem.remove_from_list([1, 2, 3, 4], 3) 129 | [1, 2, 4] 130 | 131 | iex> EctoList.ListItem.remove_from_list([1, 2, 3, 4], 1) 132 | [2, 3, 4] 133 | 134 | iex> EctoList.ListItem.remove_from_list([1, 2, 3, 4], 5) 135 | [1, 2, 3, 4] 136 | 137 | """ 138 | def remove_from_list(order_list, list_item) do 139 | Enum.reject(order_list, &(&1 == list_item)) 140 | end 141 | 142 | @doc """ 143 | Check if list item id is the first element in the ordering. 144 | 145 | iex> EctoList.ListItem.first?([1, 2, 3, 4], 1) 146 | true 147 | 148 | iex> EctoList.ListItem.first?([1, 2, 3, 4], 3) 149 | false 150 | 151 | iex> EctoList.ListItem.first?([1, 2, 3, 4], 5) 152 | false 153 | 154 | """ 155 | def first?(order_list, list_item) do 156 | List.first(order_list) == list_item 157 | end 158 | 159 | @doc """ 160 | Check if list item id is the last element in the ordering. 161 | 162 | iex> EctoList.ListItem.last?([1, 2, 3, 4], 4) 163 | true 164 | 165 | iex> EctoList.ListItem.last?([1, 2, 3, 4], 2) 166 | false 167 | 168 | iex> EctoList.ListItem.last?([1, 2, 3, 4], 5) 169 | false 170 | 171 | """ 172 | def last?(order_list, list_item) do 173 | List.last(order_list) == list_item 174 | end 175 | 176 | @doc """ 177 | Check if list item id is in the ordering. 178 | 179 | iex> EctoList.ListItem.in_list?([1, 2, 3, 4], 3) 180 | true 181 | 182 | iex> EctoList.ListItem.in_list?([1, 2, 3, 4], 5) 183 | false 184 | 185 | """ 186 | def in_list?(order_list, list_item) do 187 | Enum.member?(order_list, list_item) 188 | end 189 | 190 | @doc """ 191 | Check if list item id is in the ordering. 192 | 193 | iex> EctoList.ListItem.not_in_list?([1, 2, 3, 4], 5) 194 | true 195 | 196 | iex> EctoList.ListItem.not_in_list?([1, 2, 3, 4], 3) 197 | false 198 | """ 199 | def not_in_list?(order_list, list_item) do 200 | !Enum.member?(order_list, list_item) 201 | end 202 | 203 | @doc """ 204 | Return the list item id which is one rank higher in the ordering. 205 | 206 | iex> EctoList.ListItem.higher_item([1, 7, 3, 4], 3) 207 | 7 208 | 209 | iex> EctoList.ListItem.higher_item([1, 2, 3, 4], 1) 210 | nil 211 | 212 | iex> EctoList.ListItem.higher_item([1, 2, 3, 4], 5) 213 | nil 214 | """ 215 | def higher_item(order_list, list_item) do 216 | index = Enum.find_index(order_list, &(&1 == list_item)) 217 | 218 | case index do 219 | nil -> nil 220 | 0 -> nil 221 | _ -> Enum.fetch!(order_list, index - 1) 222 | end 223 | end 224 | 225 | @doc """ 226 | Return the list of ids above the list item id. 227 | 228 | iex> EctoList.ListItem.higher_items([1, 2, 3, 4], 3) 229 | [1, 2] 230 | 231 | iex> EctoList.ListItem.higher_items([1, 2, 3, 4], 4) 232 | [1, 2, 3] 233 | 234 | iex> EctoList.ListItem.higher_items([1, 2, 3, 4], 1) 235 | [] 236 | 237 | iex> EctoList.ListItem.higher_items([1, 2, 3, 4], 5) 238 | nil 239 | """ 240 | def higher_items(order_list, list_item) do 241 | index = Enum.find_index(order_list, &(&1 == list_item)) 242 | 243 | case index do 244 | nil -> nil 245 | 0 -> [] 246 | _ -> Enum.slice(order_list, 0, index) 247 | end 248 | end 249 | 250 | @doc """ 251 | Return the list item id which is one rank lower in the ordering. 252 | 253 | iex> EctoList.ListItem.lower_item([1, 2, 3, 7], 3) 254 | 7 255 | 256 | iex> EctoList.ListItem.lower_item([1, 2, 3, 4], 4) 257 | nil 258 | 259 | iex> EctoList.ListItem.lower_item([1, 2, 3, 4], 5) 260 | nil 261 | """ 262 | def lower_item(order_list, list_item) do 263 | index = Enum.find_index(order_list, &(&1 == list_item)) 264 | last_index = length(order_list) - 1 265 | 266 | case index do 267 | nil -> nil 268 | ^last_index -> nil 269 | _ -> Enum.fetch!(order_list, index + 1) 270 | end 271 | end 272 | 273 | @doc """ 274 | Return the list of ids below the list item id. 275 | 276 | iex> EctoList.ListItem.lower_items([1, 2, 3, 4], 2) 277 | [3, 4] 278 | 279 | iex> EctoList.ListItem.lower_items([1, 2, 3, 4], 1) 280 | [2, 3, 4] 281 | 282 | iex> EctoList.ListItem.lower_items([1, 2, 3, 4], 4) 283 | [] 284 | 285 | iex> EctoList.ListItem.lower_items([1, 2, 3, 4], 5) 286 | nil 287 | """ 288 | def lower_items(order_list, list_item) do 289 | index = Enum.find_index(order_list, &(&1 == list_item)) 290 | last_index = length(order_list) - 1 291 | 292 | case index do 293 | nil -> nil 294 | ^last_index -> [] 295 | _ -> Enum.slice(order_list, index + 1, last_index - index) 296 | end 297 | end 298 | end 299 | -------------------------------------------------------------------------------- /guides/tutorial.md: -------------------------------------------------------------------------------- 1 | # Tutorial 2 | 3 | The goal of this tutorial is to explain you how to setup ecto_list. 4 | We will use a basic example to make the process clearer. We will build a simple Serie/Video app, it will be called... **drum roll 🥁** ... Netflix . 5 | A Serie is a set of videos with a certain order. 6 | 7 | ### 1) Generating the model 8 | 9 | We will run the generators for our models: Series and Videos. 10 | 11 | mix phx.gen.html Series Serie series title items_order:array:id 12 | mix phx.gen.html Videos Video videos title serie_id:references:series 13 | 14 | We will store the videos order inside the serie with the field `:items_order`. In this example, we decide to call it "items_order" but you can change the name as you wish. 15 | Also, we didn't care much about the name of the context so we created a separate context for each model but you could definitely put them together in the same context. 16 | 17 | ### 2) Run migration 18 | 19 | Run the migration with `mix ecto.migrate`. 20 | Add the following lines in the router: 21 | 22 | ```elixir 23 | resources "/series", SerieController 24 | resources "/videos", VideoController 25 | ``` 26 | 27 | ### 3) Change schemas 28 | 29 | Add the right relationships to the models. In the Serie schema module `Netflix.Series.Serie`, add a default to items_order: 30 | 31 | ```diff 32 | defmodule Netflix.Series.Serie do 33 | # ... 34 | + alias Netflix.Videos.Video 35 | 36 | schema "lists" do 37 | field :title, :string 38 | - field :items_order, {:array, :id} 39 | + field :items_order, {:array, :id}, default: [] 40 | 41 | + has_many :videos, Video 42 | 43 | timestamps() 44 | end 45 | 46 | @doc false 47 | def changeset(video, attrs) do 48 | video 49 | - |> cast(attrs, [:title]) 50 | - |> validate_required([:title]) 51 | + |> cast(attrs, [:title, :serie_id]) 52 | + |> validate_required([:title, :serie_id]) 53 | end 54 | 55 | end 56 | ``` 57 | 58 | ```diff 59 | defmodule Netflix.Videos.Video do 60 | # ... 61 | + alias Netflix.Series.Serie 62 | 63 | schema "videos" do 64 | field :title, :string 65 | - field :serie_id, :id 66 | 67 | + belongs_to :serie, Serie 68 | 69 | timestamps() 70 | end 71 | # ... 72 | end 73 | ``` 74 | 75 | ### 4) Install `ecto_list` 76 | 77 | Add `ecto_list` to your list of dependencies in `mix.exs` (you can check the last version on hex.pm). 78 | 79 | ```elixir 80 | def deps do 81 | [ 82 | # ... 83 | {:ecto_list, "~> 0.1.2"} 84 | # ... 85 | ] 86 | end 87 | ``` 88 | 89 | ### 5) use `EctoList.Context` 90 | 91 | You can use the EctoList.Context module to add Context functions to the Serie Context. 92 | 93 | ```diff 94 | defmodule Netflix.Series do 95 | @moduledoc """ 96 | The Series context. 97 | """ 98 | 99 | import Ecto.Query, warn: false 100 | alias Netflix.Repo 101 | 102 | alias Netflix.Series.Serie 103 | 104 | + use EctoList.Context, 105 | + list: Serie, 106 | + repo: Repo, 107 | + list_items_key: :videos, 108 | + items_order_key: :items_order 109 | ``` 110 | 111 | Options: 112 | 113 | - `list`: the schema containing the list of items. Here it is Serie because each Serie can contain a list of Videos. 114 | - `repo`: the Repo module of the app 115 | - `list_items_key`: the key used in the `has_many` relationship to access the list of items 116 | - `items_order_key`: the key used in the field that contains the items order. Here it's `items_order` because that's how we decided to call it. 117 | 118 | ### 6) Preload videos 119 | 120 | Add `Repo.preload/2` to load the videos while fetching for a specific serie. 121 | 122 | ```diff 123 | - def get_serie!(id), do: Repo.get!(Serie, id) 124 | + def get_serie!(id), do: Repo.get!(Serie, id) |> Repo.preload(:videos) 125 | ``` 126 | 127 | ### 7) Change `show` action (SerieController) 128 | 129 | In the show action of the Serie Controller, add a call to `EctoList.ordered_items_list/2` which will return the list of videos ordered according the list of ids set in second position of entries. 130 | The first entry is the list of items set in the `has_many` relationship. The second entry is the list of ids which corresponds to the items order. 131 | 132 | ```diff 133 | defmodule NetflixWeb.SerieController do 134 | #... 135 | def show(conn, %{"id" => id}) do 136 | serie = Series.get_serie!(id) 137 | + videos = EctoList.ordered_items_list(serie.videos, serie.items_order) 138 | 139 | - render(conn, "show.html", serie: serie) 140 | + render(conn, "show.html", serie: serie, videos: videos) 141 | end 142 | #... 143 | end 144 | ``` 145 | 146 | ### 8) Change `show` template 147 | 148 | In the show template of Serie, add the following lines: 149 | 150 | ```diff 151 |

Show Serie

152 | 153 | 172 | 173 | <%= link "Edit", to: Routes.serie_path(@conn, :edit, @serie) %> 174 | <%= link "Back", to: Routes.serie_path(@conn, :index) %> 175 | 176 | ``` 177 | 178 | ### 9) Change `edit` and `update` action (SerieController) 179 | 180 | Back at the Serie controller, add the following lines to the edit and to the update action: 181 | 182 | ```diff 183 | defmodule NetflixWeb.SerieController do 184 | #... 185 | def edit(conn, %{"id" => id}) do 186 | serie = Series.get_serie!(id) 187 | + videos = EctoList.ordered_items_list(serie.videos, serie.items_order) 188 | 189 | changeset = Series.change_serie(serie) 190 | - render(conn, "edit.html", serie: serie, changeset: changeset) 191 | + render(conn, "edit.html", serie: serie, videos: videos, changeset: changeset) 192 | end 193 | 194 | - def update(conn, %{"id" => id, "serie" => serie_params}) do 195 | + def update(conn, %{"id" => id, "serie" => serie_params, "items_order" => items_order}) do 196 | serie = Series.get_serie!(id) 197 | + serie_params = Map.put(serie_params, "items_order", items_order) 198 | 199 | case Series.update_serie(serie, serie_params) do 200 | {:ok, serie} -> 201 | conn 202 | |> put_flash(:info, "Serie updated successfully.") 203 | |> redirect(to: Routes.serie_path(conn, :show, serie)) 204 | 205 | {:error, %Ecto.Changeset{} = changeset} -> 206 | render(conn, "edit.html", serie: serie, changeset: changeset) 207 | end 208 | end 209 | #... 210 | end 211 | ``` 212 | 213 | ### 10) Change form template for `edit` action 214 | 215 | Inside the form template of serie, add those changes: 216 | 217 | ```diff 218 | <%= form_for @changeset, @action, fn f -> %> 219 | <%= if @changeset.action do %> 220 |
221 |

Oops, something went wrong! Please check the errors below.

222 |
223 | <% end %> 224 | 225 | <%= label f, :title %> 226 | <%= text_input f, :title %> 227 | <%= error_tag f, :title %> 228 | 229 | - <%= label f, :items_order %> 230 | - <%= multiple_select f, :items_order, ["Option 1": "option1", "Option 2": "option2"] %> 231 | - <%= error_tag f, :items_order %> 232 | 233 | + <%= if @view_template == "edit.html" do %> 234 | +
235 | + <%= for video <- @videos do %> 236 | +
237 | + <%= hidden_input f, :items_order, name: "items_order[]", value: video.id %> 238 | + <%= video.id %> - <%= video.title %> 239 | +
240 | + <% end %> 241 | +
242 | + <% end %> 243 | 244 |
245 | <%= submit "Save" %> 246 |
247 | <% end %> 248 | 249 | ``` 250 | 251 | We made a simple if condition to add this block of code only if we are in the `edit` action because the form is shared also for the `new` action. 252 | 253 | ### 11) Create sample data to test 254 | 255 | We can add some data so that we can see what we get now. 256 | Inside the iex console, run: 257 | 258 | ``` 259 | Netflix.Series.create_serie(%{title: "Serie 1"}) 260 | Netflix.Videos.create_video(%{title: "Video 1", serie_id: 1}) 261 | Netflix.Videos.create_video(%{title: "Video 2", serie_id: 1}) 262 | Netflix.Videos.create_video(%{title: "Video 3", serie_id: 1}) 263 | ``` 264 | 265 | If you go to "/series" and click the first serie, you'll get the list of the 3 videos we created. Now, we will add a drag and drop library so that we can change the order. 266 | 267 | ### 12) Install Drag&Drop library 268 | 269 | For this example, I will use [draggable](https://github.com/Shopify/draggable), a library made by Shopify but you can use whatever drag and drop library. 270 | In the terminal, go to the assets folder and run `npm i @shopify/draggable`. 271 | 272 | In `assets/js`, create a file called "ectoListSorting.js" and add this content. 273 | 274 | ```js 275 | import { Sortable } from "@shopify/draggable"; 276 | 277 | export default function ectoListSorting() { 278 | const containerSelector = ".StackedList"; 279 | const containers = document.querySelectorAll(containerSelector); 280 | 281 | new Sortable(containers, { 282 | draggable: ".StackedListItem", 283 | mirror: { 284 | appendTo: containerSelector, 285 | constrainDimensions: true 286 | } 287 | }); 288 | } 289 | ``` 290 | 291 | In `assets/js/app.js`, add the following lines: 292 | 293 | ```diff 294 | // ... 295 | import "phoenix_html"; 296 | 297 | + import ectoListSorting from "./ectoListSorting"; 298 | 299 | + ectoListSorting(); 300 | // ... 301 | ``` 302 | 303 | Now back to the edit form of serie (`templates/serie/form.html.eex`), add the following changes: 304 | 305 | ```diff 306 | <%= if @view_template == "edit.html" do %> 307 | -
308 | +
309 | <%= for video <- @videos do %> 310 | -
311 | +
312 | <%= hidden_input f, :items_order, name: "items_order[]", value: video.id %> 313 | <%= video.id %> - <%= video.title %> 314 |
315 | <% end %> 316 |
317 | <% end %> 318 | 319 |
320 | <%= submit "Save" %> 321 |
322 | ``` 323 | 324 | Now, you can drag and drop the videos of a serie and save the modified order. 325 | 326 | ## Conclusion 327 | 328 | There is still a lot of code copy pasting but it's worth it because you have the control of your code. 329 | This library is pretty basic. The most important function is `EctoList.ordered_items_list/2` that render the list of items in the appropriate order. 330 | --------------------------------------------------------------------------------