arcadian
Are there accessible metaprogramming examples?
I have been reading “Polished Ruby Programming” by Jeremy Evans and am really enjoying it. He has one chapter, chapter 9, on Metaprogramming, and another, chapter 10, on DSLs.
His examples are quite accessible, like for example he starts by creating a class where, when you call it with a missing method and argument to evaluate, it uses missing_method to actually create a method returning that result. So write myclass.foo 4 + 8, and from then on myclass.foo will evaluate to 12.
There is also another example - quite funny IMO - where he creates a module named “Rusty” where you can define functions with fn instead of def, and do it in one line. So within that module you can write fn :rand, “Time.now.usec/1000000.0”, and when you call myclass.rand you get a psuedo-random number based on the time fraction.
And another example where he uses method missing at the kernel level to give ruby an always accessible words(x y z) function that returns an array of those words as symbols, i.e. [:x :y :z], although admittedly that one looked like dark magic to me.
I was wondering whether elixir had any examples like this, since I know that the language was influenced by Ruby and has similar metaprogramming capabilities. Ultimately I would like to understand how modules that create their own DSLs function, like for example how Phoenix does its routing via the module in the router.ex file.
Most Liked Responses
joey_the_snake
The best two resources I know (besides just diving into someone else’s codebase):
cloudytoday
To add to the above, official guides on macros are decent for getting going.
See the very end of the side bar for the next two chapters.
You can also just google stuff, in my experience it’s quite accessible and sometimes can even be useful.
Then, official documentation will come very handy.
BartOtten
Addendum: Read the book before the Erlangelist posts. The former is a very gentle introduction and will show you many tecniques (for your examples). The latter goes deep really fast (but goes to (dark) places the book nevers goes) ![]()
But yeah, those two are indeed all you need








