Reusing Fragments

Is reuse of fragments possible?

In an example like this

def unpublished_by_title(title) do from p in Post, where: is_nil(p.published_at) and fragment("downcase(?)", p.title) == ^title end 

It seems like it would be very convenient to be able to extract fragmentation into a separate function so that it can be reused in other places, for example:

 def unpublished_by_title(title) do from p in Post, where: is_nil(p.published_at) and downcase(p.title) == ^title end def downcase(title) do fragment("downcase(?)", ^title) end 

however, after trying a lot of different options, it doesn't seem to work because of macro extensions or anything like that. Any ideas?

+5
source share
1 answer

You are right, requests are compiled at compile time. Because of this, if you want to extend the query syntax, you need to define macros instead of regular functions.

Something like the following should do the trick:

 defmacro downcase(field) do quote do fragment("downcase(?)", unquote(field)) end end 

Remember that you need to define a macro before using it.

+5
source

Source: https://habr.com/ru/post/1238006/


All Articles