Customizing `mix phoenix.gen.*` tasks

phoenix

#1

It’s easy, but I figure a checklist might help other newbies like me.

(Is there a better place for this than some random blog?)


Write or Customize Generators
#2

I’m willing to bet the Phoenix team would like a documentation/guide PR


#3

Keep in mind though that Phoenix generators may use private APIs. So when you copy the source code, you may be depending on private APIs, implying the generator may break in future versions.

On the positive side, Phoenix allows you to customize templates without copying the generator. If you simply do step 2 and change the templates you copied, Phoenix will use the ones in your app rather than the ones it ships with:

 cp -r deps/phoenix/priv/templates/phoenix.gen.html priv/templates
 cp -r deps/phoenix/priv/templates/phoenix.gen.model priv/templates

Phoenix_gen_stealer - steal phoenix's generators for your own nefarious purposes
How to deal with phx.gen.*, when I don't need Models/Schema, in a --no-ecto webapp?
#4

Thank you. I should point out that things get even simpler if you don’t care to keep old tasks around.


#5

Maybe this could be a Phoenix feature. If you specify --templates phoenix, we would rollback to the templates in Phoenix. :smiley:


#6

Should I try implementing a mix phoenix.gen.customize? I’m thinking:

mix phoenix.gen.customize phoenix.gen.model

Would make the copies of the appropriate template files. Then there could be a --rollback option to remove them.


#7

I would prefer not to because while we make customization possible, it is not something I would like to push hard since:

  • they are meant to be learning tools most of all
  • if you copy all templates, it means we may add improvements in the future which will be dismissed (like when we migrated to ecto 2)

So I would prefer templates to be cherry-picked by developers that are comfortable with what they are doing.


#8

Sounds good.


#9

Just my 2 cents: I’m currently in the process of writing some customized context and HTML generators and in practice it’s very, very easy to isolate them from the rest of Phoenix. I’ve basically done a search and replace to bring them into my namespace and everything seems to be working. Of course it will slowly diverge from Phoenix as new Phoenix versions come out, but it’s probably not too hard to play catch up…

One can even write a meta-generator that allows you to create a package composed only of new phoenix generators under your namespace! I should do it one of these days. @pragdave’s mix_generator seems like a good starting point.


#10

I’ve written a script that steals phoenix’s generators into the current mix project: Phoenix_gen_stealer - steal phoenix’s generators for your own nefarious purposes