Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I load an elixir library in a simple elixir script?

Tags:

elixir

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.

like image 233
Sheharyar Avatar asked Jun 07 '16 12:06

Sheharyar


People also ask

What is mix EXS?

Project compilation Our mix. exs defines two public functions: project , which returns project configuration like the project name and version, and application , which is used to generate an application file.


1 Answers

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.)

like image 149
Dogbert Avatar answered Nov 16 '22 18:11

Dogbert