Selaa lähdekoodia

Turn elixir into an application that refreshes every 100ms

theenglishway (time) 2 vuotta sitten
vanhempi
commit
0e641b04f2
3 muutettua tiedostoa jossa 50 lisäystä ja 1 poistoa
  1. 11 0
      cv_gen/lib/application.ex
  2. 37 0
      cv_gen/lib/watchdog.ex
  3. 2 1
      cv_gen/mix.exs

+ 11 - 0
cv_gen/lib/application.ex

@@ -0,0 +1,11 @@
+defmodule CvGen.Application do
+  use Application
+
+  @impl true
+  def start(_type, _args) do
+    children = [{CvGen.Watchdog, []}]
+
+    opts = [strategy: :one_for_one, name: ExAccounts.Supervisor]
+    Supervisor.start_link(children, opts)
+  end
+end

+ 37 - 0
cv_gen/lib/watchdog.ex

@@ -0,0 +1,37 @@
+defmodule CvGen.Watchdog do
+  use GenServer
+  require Logger
+
+  def start_link(_), do: GenServer.start(__MODULE__, [])
+
+  @impl true
+  def init(_), do: {:ok, %{tpl_hash: "", json_hash: ""}, {:continue, :trigger_timer}}
+
+  @impl true
+  def handle_info(:timer_expired, state) do
+    state =
+      with tpl_hash <- hash("lib/templates/cv.html.eex"),
+           json_hash <- hash("lib/templates/cv.json") do
+        if tpl_hash != state.tpl_hash or json_hash != state.json_hash do
+          Logger.info("Content has changed, reloading")
+          CvGen.generate()
+          %{tpl_hash: tpl_hash, json_hash: json_hash}
+        else
+          state
+        end
+      end
+
+    {:noreply, state, {:continue, :trigger_timer}}
+  end
+
+  defp hash(path) do
+    contents = File.read!(path)
+    :crypto.hash(:md5, contents) |> Base.encode16()
+  end
+
+  @impl true
+  def handle_continue(:trigger_timer, state) do
+    Process.send_after(self(), :timer_expired, 100)
+    {:noreply, state}
+  end
+end

+ 2 - 1
cv_gen/mix.exs

@@ -14,7 +14,8 @@ defmodule CvGen.MixProject do
   # Run "mix help compile.app" to learn about applications.
   def application do
     [
-      extra_applications: [:logger, :eex]
+      mod: {CvGen.Application, []},
+      extra_applications: [:logger, :eex, :crypto]
     ]
   end