Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fragments reuse

Tags:

elixir

ecto

Is it somehow possible to reuse fragments?

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 fragment-part into a separate function so that it can be reused in other places, e.g.:

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 many different variations it seems like this wouldn't work because of macro expansions or something like that. Any ideas?

like image 954
ave Avatar asked Dec 13 '15 08:12

ave


People also ask

Can fragments be reused?

Understanding Fragments Using the support library, fragments are supported back to all relevant Android versions. Fragments encapsulate views and logic so that it is easier to reuse within activities. Fragments are standalone components that can contain views, events and logic.

Can a fragment reuse in multiple activities?

Yes you can, but you have to add more logic to your fragments and add some interfaces for each activity.

How do you reattach a fragment?

when your activity is recreated, the fragment gets destroyed. So you have to create new instance of fragment and add it again. Ok, but you cant retain the fragment view. If you want to retain the data which is in fragment, then use onSaveInstanceState() and onRestoreInstanceState() .


1 Answers

You are right, queries are composed at compile time. Because of this, if you want to extend 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 you need to define macro before you use it.

like image 123
michalmuskala Avatar answered Sep 27 '22 01:09

michalmuskala