FAQ Database Discussion Community


Why Rem operator in Elixir returns negative numbers?

elixir
I am trying a simple operation rem(-1, 25) I expect that to be the reminder of integer division and return 24 (the same e.g. as in Ruby) but it returns -1. Am I doing something wrong? Is the behavior broken on elixir?...

Setting up custom response for exception in Phoenix Application

elixir,phoenix-framework,ecto
im writing phoenix application with ecto and have the following snippet in the test {:ok, data} = Poison.encode(%{email: "[email protected]", password: "mypass"}) conn() |> put_req_header("content-type", "application/json") |> put_req_header("accept", "application/json") |> post(session_path(@endpoint, :create), data) > json_response(:not_found) == %{} this throws a Ecto.NoResultsError i have this defined defimpl Plug.Exception, for: Ecto.NoResultsError do def...

Elixir exrm release crashes on eredis start_link

erlang,elixir,exrm
I'm fairly new to Elixir and this is the first app that I'm attempting to release using exrm. My app interacts with a Redis database for consuming jobs from a queue (using exq), and also stores results of processed jobs in Redis using eredis. My app works perfectly when I...

Ecto validation fails with no error

elixir,phoenix-framework,ecto
I'm trying to create a basic CRUD app, but I'm having problems with validation. here's my controller action: def update(conn, %{"id" => id, "user" => params}) do case Repo.get(User, String.to_integer(id)) do user when is_map(user) -> user = Map.merge(user, atomize_keys(params)) case User.validate(user) do [] -> Repo.update(user) redirect conn, to: user_path(:show, user.id)...

Erlang/Elixir guards and arity

erlang,elixir,arity,pattern-guards
Is there a way to see a function's guards without seeing the source code? Given an example function (in Elixir): def divide(x, y) when y != 0 do x / y end How would one figure out that there is a guard on divide/2 without access to the source code,...

How to handle deprecation of do…end in Elixir/Phoenix after v0.9.0?

elixir,phoenix-framework
I was using Phoenix v0.9.0 until today. To get a bug fix I switched to the master branch, but now this warning appears while running mix compile: warning: using do...end in views is deprecated, please use the new YourApp.Web definitions web/view.ex:6: Youli.View (module) I'd like to do that. How can...

Is that possible to get comments with macro?

macros,elixir
I was trying to parse some code and reformat them, but it seems that quote will just ignore the comments. Is there any way to achieve this? I guess I have to dive into the erlang side?...

Phoenix - controller with multiple render

elixir,phoenix-framework
Trying to create an app with Elixir + Phoenix, that would be able to handle both "browser" and "api" requests to handle its resources. Is it possible to do it without having to do something like that : scope "/", App do pipe_through :browser resources "/users", UserController end scope "/api",...

Set default value for date selector in phoenix framework to current date

elixir,phoenix-framework
In the app I'm developing I have a date selector which will mostly be used with the current date as value (or a date a few days later). In order to reduce work for my users, I want to set today's date as default value. I can easily set the...

Does Elixir have persistent data structures similar to Clojure?

elixir
Are all immutable data structures in Elixir persistent? If not, which of them are and which not? Also, how do they compare to the persistent data structures in Clojure?

Elixir: Pattern Match or Guard

elixir
I am curious when I should be using pattern matching vs guard clauses when defining functions. For example with pattern matching: defmodule Exponent do def power(value, 0), do: 1 def power(value, n), do: value*power(value, n-1) end vs guard clause: defmodule Exponent do def power(value, n) when n==0, do: 1 def...

An example ftp session using Elixir?

elixir
I have been scouring the docs but I can't wrap my head about doing ftp in Elixir. Can someone please help give me a working example ?

What does `@type t :: %__MODULE__{}` mean in Elixir

elixir
In std Elixir packages there are a lot of lines like @type t :: %__MODULE__{} I know that @type annotation is used to alias short notation of type in @spec annotations. Altough this line is used in modules such as uri.ex which has no @spec annotations at all. What is...

elixir, ecto, compare time in the where clause

timestamp,elixir,ecto
When I create a query using ecto in Elixir, I'm not really sure about how to compare time in the 'where' clause. In the schema part I declare create_at as :datetime schema "tenant" do field :id, :integer field :created_at, :datetime # timestamps([{:inserted_at,:created_at}]) end and the query part is like def...

Rails' before_filter equivalent in Phoenix

ruby-on-rails,elixir,phoenix-framework
I've just started working on my first Phoenix app, and the issue is that I have some common lines of code in every action in my controller, that I would like to separate out. These lines fetch data from multiple Ecto Models and saves them to variables for use. In...

How to do Elixir mixins

elixir,phoenix-framework
I'm trying to create a mixins for authentication login, so it can be applied to my models which should be able to login. Much like the the has_secure_password in Ruby. Afaik this is done using the use statement which essential requires the module, and calls the __using__ macro. So I...

Loading mix dependencies marked as test only when the MIX_ENV was not originally set to “test”

elixir,mix
I wish to programmatically run the mix test task within my Elixir application. This can be done with Mix.Tasks.Test.run/1, though attempting to do so without first setting the MIX_ENV environmental variable results in the task refusing to run. We can set the env with System.put_env/2, but then the application will...

Hashset not updating

elixir
I am trying to write a web crawler and need to keep track of the visited URLs. To do this I've tried using a HashSet, but I havent been able to update it with new URLs defmodule Crawl do @depth 2 @doc """ Starts crawling process """ def start(url) do...

Phoenix: Broadcasting from IEx console

elixir,phoenix-framework
I have built a small chat app like the one here: https://github.com/chrismccord/phoenix_chat_example/blob/master/web/channels/room_channel.ex And cannot figure out how to broadcast to all users in a topic a message. In the above application (which isn't updated to v0.13 like I'm using), how would I do that? Below is what I've tried with...

What is the number that shows up after you define an anonymous function in elixir?

elixir
When you define an anonymous function in elixir you get a result like this. #Function<6.90072148/1 in :erl_eval.expr/5> What I've noticed is that the number is based on the arity of the function. So a 1 arg function is always #Function<6.90072148/1 in :erl_eval.expr/5> A two arg function is always #Function<12.90072148/2 in...

:rpc.call fails with global registered node alias

erlang,elixir
I have an Elixir project that globally registers a node using the Erlang global module: :global.register_name(:my_node, self) From another node in the cluster I can get the pid of the registered node using the global alias: :global.whereis_name :my_node However I'm unable to issue an rpc call using the global alias....

Are Elixir variables really immutable?

immutability,elixir
In Dave Thomas's book Programming Elixir he states "Elixir enforces immutable data" and goes on to say: In Elixir, once a variable references a list such as [1,2,3], you know it will always reference those same values (until you rebind the variable). This sounds like "it won't ever change unless...

(RuntimeError) expected connection to have a response

elixir,phoenix-framework
I'm a new user to Phoenix Framework and I'm trying to set up a simple HTTP POST service, that performs a calculation on incoming data and returns the result but I'm getting the following error: ** (RuntimeError) expected connection to have a response but no response was set/sent stacktrace: (phoenix)...

How to match on non-existing key of map in function head

pattern-matching,elixir
I have a function that maintains some values as state for its recursion and in order to be flexible with the order of its arguments, I am using a Map to store the state and pass it around between calls. My base case is that the function gets called without...

Disable Elixir Ecto Debug output

debugging,elixir,ecto
Whatever in iex> or using mix run -e "My.code" when I run the mix project using ecto, the Ecto's Debugging Mechanism display a bunch of SQLs like below 16:42:12.870 [debug] SELECT a0.`id` FROM `account` AS a0 WHERE (a0.`account_name` = ?) ["71000000313"] (39.6ms)` ... When I dont need the debug output...

Step List With Elixir

elixir
Can someone please provide a suggestion on how to iterate a list BUT with a batch of x at a time? For example: If the functionality existed: ["1","2","3","4","5","6","7","8","9","10"].step(5)|> IO.puts Would produce in two iterations: 12345 678910 I believe Stream.iterate/2 is the solution but my attempts to do so given an...

Read serial input until control char indicates end of message

serial-port,arduino,elixir
I'm using knewter/erlang-serial with Elixir and try to read a JSON-String (e.g. {"temperature":20.40,"humidity":30.10} coming in from an Arduino via serial input after it receives a control-signal: defmodule MyApp.SerialInput do require Logger def start_link do serial_pid = :serial.start [{:open, "/dev/cu.usbmodem1431"}, {:speed, 115200}] control_signal = "1" :timer.send_interval 5000, serial_pid, {:send, control_signal} wait_for_new_values...

How does Polymorphic association work with Ecto?

elixir,phoenix-framework
Ecto seems to support polymorphic association as I read through https://github.com/elixir-lang/ecto/issues/389 and its related issues linked from it. Let's say I need a Comment model association on Task and Event models. If my understanding of Ecto association with custom source is right, then we need four tables and three models,...

elixir Logger for lists, tuples, etc

logging,elixir
I can use the elixir logger for inspecting strings > str = "string" > Logger.info "Here is a #{str}" [info] Here is a string But when I log a list, it doesn't look pretty > list = [1,2,3,4,5] > Logger.info "Here is a list: #{list}" [info] Here is a list:...

How to Log something in Controller when Phoenix Server is running?

elixir,phoenix-framework
Well, the question is pretty clear. I'm trying to print some debug information from one of my Controllers in my Phoenix App when the Server is running. defmodule PhoenixApp.TopicController do use PhoenixApp.Web, :controller alias PhoenixApp.Topic plug :action def index(conn, _params) do # ... log "this text" # ... render(conn, "index.html")...

Why did elixir change the notation for sending a message to a process?

elixir
I noticed that in elixir version 0.10.1, you send a message to a process like this my_process <- :message, self But now in elixir 1.0.2, you send a message to a process like this Process.send my_process, :message, self What was the reason for this change?...

How to rewrite Erlang combinations algorithm in Elixir?

functional-programming,erlang,elixir
I've been tinkering with Elixir for the last few weeks. I just came across this succinct combinations algorithm in Erlang, which I tried rewriting in Elixir but got stuck. Erlang version: comb(0,_) -> [[]]; comb(_,[]) -> []; comb(N,[H|T]) -> [[H|L] || L <- comb(N-1,T)]++comb(N,T). Elixir version I came up with...

Importing test code in elixir unit test

elixir,mix
I'm writing tests of some Elixir code that interacts with SSH. In my tests, I'd like to start an SSH server that I can run my code against. I'd prefer to store this code in it's own file in the test directory, and have it imported by various different tests....

Parsing xml with xmerl

xml,elixir
I'm trying to parse a xml structure like this <result> <event> <title>My event</name> <artist> <name>Michael Jackson</name> </artist> </event> <event> <title>My event 2</name> <artist> <name>Rolling Stones</name> </artist> </event> <result> So i want to traverse the events, and end up with a Elixir map with the corresponding result. It needs to be...

How to delete a Phoenix Session?

elixir,phoenix-framework
I'm going through the Phoenix Guide on Sessions. It explains it very well how I can bind data to a session using put_session and fetch the value later using get_session but it doesn't tell how I can delete a User's session. From the guide: defmodule HelloPhoenix.PageController do use Phoenix.Controller def...

Elixir/Phoenix: Missing beam file elf_format <<“/usr/lib/erlang/lib/hipe-3.11.2/ebin/elf_format.beam”

elixir,phoenix-framework
While trying to compile a release of my Phoenix project, the following error comes up: $ mix release .... ==> Generated .appup for myapp 0.0.1 -> 0.0.2 ===> Missing beam file elf_format <<"/usr/lib/erlang/lib/hipe-3.11.2/ebin/elf_format.beam">> could not find app plug {0,10,0} $ elixir --version Elixir 1.0.3 The Phoenix version is 0.10.0. Am...

How to put key value pair into map with variable key name

elixir
I'm trying to end up with a single map containing many different preferences, it should look like this: %{some_preference_name:%{foo:"bar"},another_preference_name:%{foo:"bar"}} I have a list of preference maps from the database, and I need to get through them and set the "preference" field as the key with the various values as the...

Setting up Phoenix Framework and Ecto to use UUIDs: how to insert the generated value?

postgresql,elixir,phoenix-framework,ecto
A few days ago I started using Elixir and the Phoenix Framework (v 0.12.0) with a Postgres database. I'm trying to create a table which has a UUID primary key, which I prefer over the sequential default. After using mix phoenix.gen.html to generate the model and migration files and following...

parameterized enumerable type in elixir typespecs

types,elixir
Is it possible to parametrize the Enumerable.t type in elixir? so currently I have a function that takes a list of foos: @spec the_awesome([foo]) :: any def the awesome(foos) do Enum.reduce(foos, &(bar(&2, &1))) end and really it does not have to be a list! since the only function call is...

Using Elixir, erlport with Python 2.7.9, receiving an arity error

python,elixir,arity,beam
I am trying to use Python with Elixir and I wrote the following functional code (you can find the repo I'm building here: https://github.com/arthurcolle/elixir_with_erlport) defmodule Snake do use Application def start(_type, _args) do import Supervisor.Spec, warn: false children = [ # Define workers and child supervisors to be supervised #...

Should I use Mix.Utils in my elixir code?

elixir,mix
I need to get a file by URL and store it on the local disk. I see that Mix.Utils has: copy_path!(source, target, opts \\ []) Which seems to do exactly what I want, but is Mix.Utils only something you'd use for writing mix tasks and not for general problem solving?...

how to instruct ecto to not create the auto increment id field?

elixir
Ecto migrations automatically create an auto increment field by name 'id' in the table. How to avoid creating this field? How to set another column in the table as primary key (not auto increment)? ...

How to read and write id3v1 and id3v2 tags in Elixir

erlang,mp4,elixir,id3
I would like to scan music files and read/write metadata using Elixir (this whole project is about learning Elixir - so please don't tell me to use Python!). As I understand it, I have two choices: call a system utility or (as no libraries exist in Erlang or Elixir that...

Most efficient way to search file for byte patterns in Elixir

elixir,id3
I am searching for id3 tags in a song file. A file can have id3v1, id3v1 extended tags (located at the end of the file) as well as id3v2 tags (usually located at the beginning). For the id3v1 tags, I can use File.read(song_file) and pull out the last 355 bytes...

Phoenix Framework before filter

elixir,phoenix-framework
Does the Phoenix Framework employ any types of callback filter such as those found in Rails? I know it is possible to validate changesets, but I am looking for ways to implement actions such as before_create, before_save and after_commit.

Sort List elements in Elixir Lang

elixir
I have a list of strings that I want to order in two ways. Alphabetically By string length ...

Why Phoenix doesn't use Plug to start the server?

elixir,phoenix-framework
liveforeverx on irc has answered my original question and I have modified this question as a followup. Phoenix depends on Plug for many of its function. However, when it comes to starting cowboy server, why doesn't Phoenix start it using Plug's api in Phoenix.Endpoint.CowboyHandler.start_link? Why does start_link on ranch_listener_sup is...

Pushing operations to a message queue for processing when able to

elixir,phoenix-framework
My title isn't great because I'm finding it hard to explain what I want in a small snippet...soo I'll try in depth! I'm writing an Elixir app using the Phoenix web framework. What I want to do is this: Call a web route, which phoenix handles and passes off to...

How Can We Clear the Screen in Iex on Windows

windows,elixir
Please how can we clear the screen in Iex on Windows Documented method in Iex help does not work: clear/0 — clears the screen This StackOverflow Answer also does not work in Windows....

Where can I put my Plugs and then use them from different controllers in my Phoenix app?

elixir,phoenix-framework
I'm creating my first Elixir-Phoenix app. I've written a few plugs that I want to use in multiple controllers, right now there is a lot of code duplication since the Plug code is being repeated in all of my controllers. My question is, is there a file where I can...

Elixir - Looping through and adding to map

enumeration,elixir
I'm rebuilding something in Elixir from some code I built in C#. It was pretty hacked together, but works perfectly (although not on Linux, hence rebuild). Essentially what it did was check some RSS feeds and see if there was any new content. This is the code: Map historic (URL...

Elixir Macro: Power ** function

macros,elixir
Looking through the Elixir source I see that multiplication is defined like this: @spec (number * number) :: number def left * right do :erlang.*(left, right) end I wanted to make a ** function to do power as an exercise. However, when I try, I get an exception and I...

“an adapter was given to :pubsub but no :name was defined” with Elixir/Phoenix after v0.9.0

elixir,phoenix-framework
This error comes up when running mix compile after switching to Phoenix master after starting with v0.9.0: == Compilation error on file lib/youli/endpoint.ex == ** (ArgumentError) an adapter was given to :pubsub but no :name was defined, please pass the :name option accordingly lib/youli/endpoint.ex:2: (module) (stdlib) erl_eval.erl:657: :erl_eval.do_apply/6 I haven't...

Elixir Remove Duplicates From List

elixir
Would someone be willing to provide some alternate solution to the removal of duplicate values from a List (X) using Functional Programming and Elixir Constructs? X = [1,26,3,40,5,6,6,7] # the 6 being the duplicate The stock solution in my mind for solving this problem, would be to iterate the list...

Querying by DateTime in Ecto

elixir,phoenix-framework,ecto
Here is what I have tried. date = Ecto.DateTime.from_erl(:calendar.universal_time()) query |> where([record], record.deadline >= ^date) I also tried date = Ecto.DateTime.from_erl(:calendar.universal_time()) query = from m in MyApp.SomeModel, where: m.deadline >= ^date, select: m Both return same message value `%Ecto.DateTime{..}` in `where` cannot be cast to type :datetime in query From...

In Elixir/Phoenix, after template change, “cannot define module MyApp.PageView because it is currently being defined”

elixir,phoenix-framework
I just changed an image path in a template in my Phoenix app and reloaded the page. This error message appeared in the browser: CompilationError at GET / Showing console output == Compilation error on file web/views/page_view.ex == ** (CompileError) web/views/page_view.ex:1: cannot define module Youli.PageView because it is currently being...

where's the elixir dependencies respository?

elixir
In an elixir project mix.exs file, we include the dependencies like so defp deps(_) do [ {:phoenix, "~> 0.6.1"}, {:ecto, "~> 0.2.0"} ] end Where's the repository that stores the elixir code for these dependencies? Coming from a Ruby background, the deps function is analagous to a Gemfile. But I...

Can function application be overriden with Macro in Elixir?

metaprogramming,elixir
Let's say I'd want to override each function call with a macro that counts how many times I called each particular function. Is it possible in Elixir? I know there is a possibility of overriding builtin macros and functions with import Kernel, except: [name: arity] import MyOwnKernel But it doesn't...

How can I handle the empty case in Elixir/Phoenix templates?

elixir,phoenix-framework
In a template I have an iteration over some days in an itinerary: <%= for day <- @days do %> <tr> <td><%= day.number %></td> <td><%= day.main_event_time %></td> <td><%= day.main_event %></td> <td><%= day.location %></td> <td><%= day.who %></td> <td><%= day.summary %></td> <td><%= day.lodging %></td> <td><%= link "Show", to: day_path(@conn, :show, day) %></td>...

What does BEAM stand for in iex for the Elixir programming language?

architecture,elixir,acronym,beam,lightweight-processes
I'm sort of curious as to what the B. E. A. and M. stand for. I recall seeing an explanation of the acronym BEAM, but I have not managed to find it again. It comes up in error codes: ➜ gentoo iex Erlang/OTP 17 [erts-6.4.1] [source] [64-bit] [smp:8:8] [async-threads:10] [kernel-poll:false]...

How strict should one be when defining guards for function clauses?

elixir
How strict should I be when I define my function clauses? Elixir allows writing function heads in a range from no guards over check types up to verify value within range. So for example I don't know what style to use in a function like this: def measure(args = %{times:...

How can I exit quietly from Elixir?

elixir
Process.exit(self, :normal) does the job, but it prints out ** (EXIT from #PID<0.49.0>) normal. Is there a way to exit without the message?

How do I find the workers in my Elixir application?

elixir,otp
Working through the Supervisor and Application part of the Getting Started tutorial, I'm writing a unit test for the supervision tree problem at the bottom. I tried starting the top-level supervisor but it failed with this error: 1) test all buckets die if registry dies (KV.SupervisorTest) test/kv/supervisor_test.exs:4 ** (EXIT from...

Chunking list based on struct type changing

elixir
I have a list I want to chunk up based on a transition from struct type B to A. So for example, I have the following: iex(1)> defmodule A, do: defstruct [] {:module, A ... iex(2)> defmodule B, do: defstruct [] {:module, B ... iex(3)> values = [ %A{}, %A{},...

Horribly redundant Phoenix controller

elixir,phoenix-framework,ecto
I'm doing my first Phoenix application, and trying to do new/2 controller. The code I wrote is def new(conn, %{"fbid" => fbid, "latitude" => lat, "longitude" => lng, "content" => content}) do {fbid, _} = Integer.parse(fbid); {lat, _} = Float.parse(lat); {lng, _} = Float.parse(lng); chats = %Chat{:fbid => fbid, :latitude...

Why the syntax for defining sigils in Elixir doesn't use “defsigil”?

elixir,sigils
I was reading the page about sigils in the Elixir tutorial. I expected the syntax for defining sigils uses "defsigil" just like "defstruct", "defprotocol", and so on. But it was not so. Why?

receiving :badarg on File.write

elixir
I am starting to learn Elixir, and this is also my first dynamic language, so I am really lost working with functions without type declaration. What I am trying to do: def create_training_data(file_path, indices_path, result_path) do file_path |> File.stream! |> Stream.with_index |> filter_data_with_indices(indices_path) |> create_output_file(result_path) end def filter_data_with_indices(raw_data, indices_path) do...

Elixir - Get Host By Name?

elixir
How do you gethostbyname with Elixir? There doesn't seem to be a supported API and the two solutions seem to revolve around, Erlang's Inet Fork to shell with System (hostname) ...

Does spawning new processes use all CPU cores in elixir

elixir
Suppose, I'm on a 4-core CPU machine. If I run the following in my elixir VM: 1..4 |> Enum.map fn(x) -> spawn(computationally_heavy_process) end Does this use all 4 cores of my machine. One of each of the computationally heavy processes?...

Join two tables belong to two database in Elixir Ecto

elixir,ecto
In Elixir, with Ecto, is it possible to join two different tables (in the same host) belonging to different two databases. There are two databases called cloud and cloud_usage in this query When I execute the query, which Repo should I use? Billing.CloudUsage.Repo.all(query) or Billing.Cloud.Repo.all(query) query = from cucu in...

“Cannot begin test transaction because we are already inside one”

elixir,phoenix-framework,ecto
I followed this tutorial and my simple test always fail with this error 1) test /index returns a list of contacts (WorldNote.ChatsControllerTest) test/controllers/chats_controller_test.exs:16 ** (RuntimeError) cannot begin test transaction because we are already inside one stacktrace: (ecto) lib/ecto/adapters/sql.ex:321: anonymous fn/6 in Ecto.Adapters.SQL.start_test_transaction/3 (ecto) lib/ecto/adapters/sql.ex:615: Ecto.Adapters.SQL.pool_transaction/4 (ecto) lib/ecto/adapters/sql.ex:314: Ecto.Adapters.SQL.start_test_transaction/3...

Is it possible to stub(mock?) Ecto.UUID.generate in an ExUnit test?

unit-testing,elixir,phoenix,ecto
I'm using Ecto.UUID.generate to create a random token on a user model. In my ExUnit test, I want to test the controller that calls the creation route, however because the token is always random, I can't deterministically test the result. Ideally, I want to be able to stub the Ecto.UUID.generate...

Where does Elixir/erlang fit into the microservices approach? [closed]

architecture,erlang,docker,elixir,microservices
Lately I've been doing some experiments with docker compose in order to deploy multiple collaborating microservices. I can see the many benefits that microservices provide, and now that there is a good toolset for managing them, I think that it's not extremely hard to jump into the microservices wagon. But,...

Getting a sibling process in Elixir

erlang,elixir,otp
I have an Elixir/Erlang process tree: parent (Supervisor) ├── child1 (GenServer) └── child2 (GenServer) child1 (a DB client) has information that child2 needs to use. What's a good way to pass a reference from the Supervisor process to child2 so that child2 will always have a valid reference to child1?...

Elixir ecto connect to an existing DB

elixir,ecto
After doing some research in the link below https://github.com/elixir-lang/ecto/tree/master/examples/simple I am a little confused about how to use ecto in elixir. There is always a schema declared like defmodule Weather do use Ecto.Model schema "weather" do field :city, :string field :temp_lo, :integer field :temp_hi, :integer field :prcp, :float, default: 0.0...

Another way to exiting IEX other than ctrl-C

elixir
I know we can exit the IEX console with control-C. I'm curious if there's a command to type into the console that would also do the same thing.

How can I do a line break (line continuation) in Elixir?

syntax,elixir
In Python, for example, one can break line with '\' character (yeah, necessary evil). Is it possible to break lines in Elixir?

Elixir - Download a File (Image) from a URL

elixir
What does the code to download a file/image from a URL look like in Elixir? Google searches seem to bring back how to download Elixir itself....

Wait for Node.connect before using :global.whereis_name

erlang,elixir
I have the following function: def join(id) do if Node.connect(:"#{id}@127.0.0.1") do send :global.whereis_name(id), {:join, id} end end I receive the error: (ArgumentError) argument error :erlang.send(:undefined, ... which I assume is because Node.connect does some gathering of information and when I call :global.whereis_name it has not finished yet. If I throw...

How can I build an Elixir escript that does not halt the Erlang VM after execution (like elixir --no-halt)

erlang,elixir,erlang-escript
I have a program that starts the application and then adds (children) workers to a supervisor. Obviously after doing only that it has nothing more left to do and it halts (exits). So making it not halt the VM would allow the workers to work. The only solution I have...

With Elixir Ecto, how do I add a has_many relationship in a migration?

elixir,ecto
I want to write something like this: defmodule JobHunt.Repo.Migrations.CompaniesHaveManyJobs do use Ecto.Migration def change do alter table (:companies) do add :jobs, :has_many, Job end end end Running mix ecto.migrate with this migration gives an error, so what is the right way to do this?...

Elixir How to convert a Map struct to a Record struct

elixir
I have a Record struct and a Map struct like: defmodule Foo.Bar do defstruct boo: nil, baz: nil end defmodule Foo do require Record Record.defrecord :bar, Foo.Bar, [boo: nil, baz: nil] end I can convert the Record to Map like this: defp update_map({k, v}, map), do: Map.update!(map, k, fn(_) ->...

Matching on part of a binary in a method signature

pattern-matching,elixir
I'm reading a binary file, and within it there is a structure where the first byte of data indicates the type of data following it. I'm trying to handle this via pattern matching, and am having trouble. I've tried a few ways I figured may work, none of which do....

How to remove elixir package on hex

elixir,hex-pm
I want to remove published elixir package on hex. I already know that I can only delete it up to one hour after creation with this command. mix hex.publish --revert VERSION But, Is there another way to delete package that is over one hour after creation on hex ? Thanks...

How would one run a functions with same name?

elixir
I am new Elixir and really enjoying it. I hit a wall when trying to use functions with same name. Here is an example defmodule ChangeName do def convert(:captilize, name), do: String.capitalize(name) def convert(:lower, name), do: String.downcase(name) end I am using iex and the basic calls where ChangeName.convert.captilize but how...

Optional POST parameters in Elixir Phoenix

elixir,phoenix-framework
I have a phoenix route that I want to POST some form data to, however there are about 4 fields of the form that are optional (the form is constructed by the end user and therefore these fields may not exist in the POST payload) In the Phoenix controller for...

How to stub (or prevent running) of a call to a worker in my ExUnit test?

elixir,phoenix-framework
I have a Phoenix app (which is just a restful api with no front end) and one of the controllers does some stuff which I want to test, but at the end of the controller it calls a dispatcher which sends a payload off to a worker (run under poolboy)...

In Elixir how do you initialize a struct with a map variable

elixir,elixir-framework
I know its possible to create a struct via %User{ email: '[email protected]' }. But if I had a variable params = %{email: '[email protected]'} is there a way to create that struct using that variable for eg, %User{ params }. This gives an error, just wondering if you can explode it...

How to run Elixir application?

elixir
What is the correct way to run an Elixir application? I'm creating a simple project by: mix new app and after that I can do: mix run which basically compiles my app once. So when I add: IO.puts "running" in lib/app.ex I see "running" only for the first time, each...

Updating user supplied params before writing to db in Ecto

elixir
Here is my User model @required_fields ~w(name email hashed_password) @optional_fields ~w() def changeset(model, params \\ nil) do model |> cast(params, @required_fields, @optional_fields) |> validate_length(:password, min: 6) |> hash_password(params["password"]) end def hash_password(changeset, password) do put_change(changeset, :hashed_password, Bcrypt.hashpwsalt(password)) end This is the code from the controller changeset = User.changeset(%User{}, user_params) I'm trying...

Elixir File.read returns empty data when accessing /proc/cpuinfo

erlang,elixir
When running any thing like File.read "/proc/cpuinfo" >> {:ok, ""} Same for equivalent erlang function. Is there some reason for this pattern?...

Generate a sequence of N natural numbers

elixir
In Ruby it is possible to do so using a splat [*1..5] # => [1, 2, 3, 4, 5] How can this be done in Elixir? I know that I could probably use reduce but maybe there is an easier way?...

Output tabular data with IO.ANSI

elixir
I would like to render a 2-dimensional list to a nice tabular output, using an ANSI escape sequences to control the formatting. So given this data: data = [ [ 100, 20, 30 ], [ 20, 10, 20 ], [ 50, 400, 20 ] ] I would like to output...

How to Display a single backslash in Elixir string

elixir
Can somebody tell me how to add a single backslash in the SQL statement in Elixir iex(1)> sql = "select * from user limit 1 \G;" "select * from user limit 1 G;" iex(2)> sql = "select * from user limit 1 \\G;" "select * from user limit 1 \\G;"...

When to use compile-only dependencies in Elixir

elixir,exrm
When would it be appropriate to specify a dependency only in deps in my mix.exs and not as a runtime dependency in applications? I thought that applications are actual applications that need to be started before my own application can be started, but I run into a problem where exrm...

Elixir private function dynamic call

dynamic,elixir
I've found Kernel.apply/3 which allows dynamically calling a public method in a module by specifying the method as an atom, e.g. result = apply(__MODULE__, :my_method, [arg]) translates to result = my_method(arg) What baffles me is a way to call a private method; Given code like this: defmodule MyModule do def...

How to pack / unpack a hex string (high nibble first) with Elixir

hex,elixir
I was wondering how I would work with hex strings in Elixir. Specifically, I'm interested in converting from Hex to ASCII. In Ruby, an implementation of this may be: ["001C7F616A8B002128C1A33E8100"].pack('H*').gsub(/[^[:print:]]/, '.') How would I accomplish this task with Elixir? I have tried: <<00, 01, C7, F6...>> but this isn't a...

Which OTP behavior should I use for an “endless” repetition of tasks?

elixir,otp,phoenix-framework
I want to repeatedly run the same sequence of operations over and over again next to a Phoenix application (without crashing the whole web-app if something brakes in the worker of course) and don't really know wether I should use a GenServer, Elixir's Tasks, an Agent or something completely different...

is it possible in Elixir to make a http POST request pushing some data to an external URL?

elixir
I have an external URL (third party code) that I want to POST some data to, I don't have to wait for a response. How would I do this in Elixir (if possible at all?) Effectively I want to cURL some data to an external url...

How to start phoenix.server as daemon

elixir,phoenix-framework
The below command run the phoenix.server in production mode and is given as the command for deploying phoenix. MIX_ENV=prod PORT=4001 iex -S mix phoenix.server However, the above command run the server interactively and closing the terminal, stops the phoenix.server from running. How to have phoenix.server run in the background? ...