Reputation: 75760
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.
Upvotes: 11
Views: 2420
Reputation: 1269
You can use Mix.install
, introduced in Elixir 1.12. It works in scripts, no Mix project required.
# Install the dependencies you want directly in the script
Mix.install([:httpoison])
# Call modules from installed libraries
HTTPoison.get("https://stackoverflow.com/")
Upvotes: 4
Reputation: 93
By using erun
, you can virtually install global Mix packages.
https://github.com/s417-lama/erun
Upvotes: -1
Reputation: 222188
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.)
Upvotes: 6
Reputation: 769
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.
Upvotes: 1