Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to put helper functions in a phoenix project?

Tags:

In a phoenix / elixir project: What is a good place to put helper functions. For example: I use Timex to deal with dates but I have to do some transformations on the returned struct to use it with my DB driver (one uses the key :min, the other :minute, etc). I don't want to repeat this piece of code in every model and would write a simple function that does that. What would be a good place to put this? Just in a module within the /lib folder? Are there any guidelines on how to organize this?

like image 264
Ole Spaarmann Avatar asked Nov 26 '15 12:11

Ole Spaarmann


People also ask

What is meant by helper function?

A "helper function" is a function you write because you need that particular functionality in multiple places, and because it makes the code more readable. A good example is an average function. You'd write a function named avg or similar, that takes in a list of numbers, and returns the average value from that list.


1 Answers

I don't think there are guidelines yet. You can create modules grouped by topic, like MyApp.TimexHelpers and then import those at the places you actually want to use the helpers.

The main difference between lib and web for Phoenix before 1.2 is the reloading behaviour. For changes under lib to take effect you need to restart your server. So I tend to put most stuff under web to make development easier. Maybe web/helpers...

Since Phoenix 1.2 "the lib/ directory is now code reloaded by default along with web/ in development". See Changelog.

like image 96
manukall Avatar answered Sep 30 '22 18:09

manukall