9
votes

In ruby scripts, I could simply do:

require 'some-gem'

SomeGem.do_something!

How can I do something similar in elixir exs scripts without creating a brand new mix project? So far I've searched google on ways to do this, and read a few blog posts (such as this), but can't figure out a proper (read 'simple') way to do this.

Specifically, I want to use HTTPoison in my elixir script.

3

3 Answers

5
votes

There are no global package installs in Elixir like there are in Ruby. While it might be technically possible to compile the dependencies into .beam files and add them to the load path of your scripts (like the article you linked to does), if you want behavior somewhat similar to Ruby, I would recommend you to make use of mix run to run arbitrary scripts with all the project dependencies loaded.

Create one global mix project with all the dependencies you want specified in mix.exs, write your code in any .exs file (doesn't have to be in the same folder), and execute it by

cd /path/to/mix/project && mix run /path/to/.exs

You could even create a wrapper shell script to automatically do the above by just invoking my-elixir script.exs.

(I regularly do this while testing code for answers here on StackOverflow which use some common dependencies like HTTPoison and/or Poison.)

1
votes

Without mix, this could be a little complex, but doable.

I think you have to explicitly adding the path where HTTPoison is compiled on the top of your exs script.

Elixir provides an API Code.expand_path to prepend a path to the beginning of the Erlang VM code path list. You could find more description about the API here.

-1
votes

By using erun, you can virtually install global Mix packages.

https://github.com/s417-lama/erun