Elixirの開発元であるPlatformatecからEcto2.0に関するフリーペーパーが正式に公開された。
Click to access whats-new-in-ecto-2-0-1.pdf
いくつかEctoの特性(Ecto is not your ORMといったこととか)が書かれていて、解決したい問題とその対策として2.0や2.1で入ったことを書いている。
1つ、気になったところをメモとして残しておく。
Ecto2.1からdynamicを使って簡易に動的にwhere句を制御することができるようになった。コードは以下。
https://github.com/elixir-ecto/ecto/blob/v2.1.1/lib/ecto/query.ex#L381
例えば、以下の場合は dynamic で指定した箇所をその引数の状態によって動的に切り替えることができる。
(http://blog.plataformatec.com.br/wp-content/uploads/2016/12/whats-new-in-ecto-2-0-1.pdf より)
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
| def filter(params) do | |
| Post | |
| |> order_by(^filter_order_by(params["order_by"])) | |
| |> where(^filter_where(params)) | |
| |> where(^filter_published_at(params["published_at"])) | |
| end | |
| def filter_order_by("published_at_desc"), do: [desc: :published_at] | |
| def filter_order_by("published_at"), do: [asc: :published_at] | |
| def filter_order_by(_), do: [] | |
| def filter_where(params) do | |
| for key <- [:author, :category], | |
| value = params[Atom.to_string(params)], | |
| do: {key, value} | |
| end | |
| def filter_published_at(date) when is_binary(date), | |
| do: dynamic([p], p.published_at > ^date) | |
| def filter_published_at(_date), | |
| do: true |
これにより、SQLの発行を静的に数多くのパターン実装する必要のある箇所を、限られた少数の実装で表現することができるようになる。個人的に、特にfilter系の関数用意しようとしたら必要以上に行数が増える状態になっていたのでとてもありがたい。時間見つけて適用してみよう。