Elixir言語とPhoenix Frameworkを使った実用的なプログラミング学習アプリケーションです。HTMXを活用してモダンな非同期Webアプリケーションの構築方法を体験できます。
# 整数と浮動小数点
age = 25
height = 175.5
# 原子(アトム)- 名前が値となる定数
status = :ok
error = :error
# 文字列
name = "Elixir"
message = "Hello, #{name}!"
# リスト
numbers = [1, 2, 3, 4, 5]
mixed_list = [1, "hello", :atom, 3.14]
# タプル
coordinates = {10, 20}
result = {:ok, "success"}
# マップ
user = %{name: "Alice", age: 30, email: "alice@example.com"}
# キーワードリスト
options = [debug: true, timeout: 5000]# 基本的なマッチング
{:ok, result} = {:ok, "成功"}
[head | tail] = [1, 2, 3, 4] # head = 1, tail = [2, 3, 4]
# 関数定義でのパターンマッチ
def handle_result({:ok, data}), do: "成功: #{data}"
def handle_result({:error, reason}), do: "エラー: #{reason}"
# case文でのパターンマッチング
case File.read("file.txt") do
{:ok, content} -> process_content(content)
{:error, :enoent} -> "ファイルが見つかりません"
{:error, reason} -> "読み込みエラー: #{reason}"
end# 基本的な関数
def greet(name) do
"Hello, #{name}!"
end
# ワンライナー関数
def add(a, b), do: a + b
# ガード節付き関数
def factorial(n) when n <= 1, do: 1
def factorial(n) when n > 1, do: n * factorial(n - 1)
# プライベート関数
defp helper_function(data) do
# モジュール内でのみ使用可能
end# 従来の書き方
result = String.downcase(String.trim(" HELLO WORLD "))
# パイプライン演算子を使用
result = " HELLO WORLD "
|> String.trim()
|> String.downcase()
# リスト処理での活用
numbers = [1, 2, 3, 4, 5]
sum = numbers
|> Enum.map(&(&1 * 2)) # [2, 4, 6, 8, 10]
|> Enum.filter(&(&1 > 5)) # [6, 8, 10]
|> Enum.sum() # 24list = [1, 2, 3, 4, 5]
# よく使用されるEnum関数
Enum.map(list, fn x -> x * 2 end) # [2, 4, 6, 8, 10]
Enum.filter(list, fn x -> x > 3 end) # [4, 5]
Enum.reduce(list, 0, fn x, acc -> x + acc end) # 15
Enum.sum(list) # 15
Enum.max(list) # 5
Enum.min(list) # 1
# 短縮記法
Enum.map(list, &(&1 * 2))
Enum.filter(list, &(&1 > 3))Phoenix は Model-View-Controller パターンを採用:
- Model: データとビジネスロジック(Ecto スキーマ)
- View: データの表示とテンプレート(HTML、JSON)
- Controller: リクエスト処理とレスポンス生成
defmodule MyAppWeb.PageController do
use MyAppWeb, :controller
# GET /
def index(conn, _params) do
render(conn, :index, page_title: "ホーム")
end
# POST /create
def create(conn, %{"user" => user_params}) do
case create_user(user_params) do
{:ok, user} ->
conn
|> put_flash(:info, "ユーザーが作成されました")
|> redirect(to: ~p"/users/#{user.id}")
{:error, changeset} ->
conn
|> put_flash(:error, "エラーが発生しました")
|> render(:new, changeset: changeset)
end
end
end# lib/my_app_web/router.ex
defmodule MyAppWeb.Router do
use MyAppWeb, :router
pipeline :browser do
plug :accepts, ["html"]
plug :fetch_session
plug :fetch_live_flash
plug :put_root_layout, html: {MyAppWeb.Layouts, :root}
plug :protect_from_forgery
plug :put_secure_browser_headers
end
scope "/", MyAppWeb do
pipe_through :browser
get "/", PageController, :index
get "/users", UserController, :index
post "/users", UserController, :create
# RESTful リソース
resources "/posts", PostController
end
end# lib/my_app_web/controllers/page_html/index.html.heex
<div class="container">
<h1><%= @page_title %></h1>
<%= for item <- @items do %>
<div class="item">
<h3><%= item.title %></h3>
<p><%= item.description %></p>
</div>
<% end %>
<.link href={~p"/items/new"} class="btn btn-primary">
新しいアイテムを追加
</.link>
</div>my_phoenix_app/
├── _build/ # コンパイル済みファイル
├── assets/ # フロントエンド資産
│ ├── css/
│ │ └── app.css # メインスタイルシート
│ ├── js/
│ │ └── app.js # JavaScript エントリーポイント
│ └── vendor/ # サードパーティライブラリ
├── config/ # 設定ファイル
│ ├── config.exs # 基本設定
│ ├── dev.exs # 開発環境設定
│ ├── prod.exs # 本番環境設定
│ ├── runtime.exs # 実行時設定
│ └── test.exs # テスト環境設定
├── deps/ # 依存関係ライブラリ
├── lib/ # メインのアプリケーションコード
│ ├── my_app/ # ビジネスロジック
│ │ ├── application.ex # アプリケーション起動モジュール
│ │ ├── repo.ex # データベースリポジトリ
│ │ └── schemas/ # データベーススキーマ
│ └── my_app_web/ # Web関連コード
│ ├── components/ # 再利用可能なコンポーネント
│ │ ├── core_components.ex
│ │ └── layouts.ex
│ ├── controllers/ # コントローラー
│ │ ├── page_controller.ex
│ │ └── page_html/ # HTMLテンプレート
│ │ └── index.html.heex
│ ├── endpoint.ex # HTTPエンドポイント
│ ├── gettext.ex # 国際化
│ ├── router.ex # ルーティング
│ └── telemetry.ex # メトリクス収集
├── priv/ # プライベート資産
│ ├── gettext/ # 翻訳ファイル
│ ├── repo/ # データベースマイグレーション
│ │ └── migrations/
│ └── static/ # 静的ファイル(画像、CSS、JSなど)
├── test/ # テストファイル
│ ├── my_app_web/
│ │ └── controllers/
│ ├── support/
│ └── test_helper.exs
├── mix.exs # プロジェクト設定とライブラリ依存関係
└── README.md
defmodule MyApp.MixProject do
use Mix.Project
def project do
[
app: :my_app,
version: "0.1.0",
elixir: "~> 1.14",
deps: deps()
]
end
def application do
[
mod: {MyApp.Application, []},
extra_applications: [:logger, :runtime_tools]
]
end
defp deps do
[
{:phoenix, "~> 1.7.0"},
{:phoenix_html, "~> 3.3"},
{:phoenix_live_reload, "~> 1.2", only: :dev},
{:telemetry_metrics, "~> 0.6"},
{:telemetry_poller, "~> 1.0"},
{:jason, "~> 1.2"},
{:bandit, "~> 1.0"}
]
end
enddefmodule MyApp.Application do
use Application
def start(_type, _args) do
children = [
MyAppWeb.Telemetry,
{DNSCluster, query: Application.get_env(:my_app, :dns_cluster_query) || :ignore},
{Phoenix.PubSub, name: MyApp.PubSub},
MyAppWeb.Endpoint
]
opts = [strategy: :one_for_one, name: MyApp.Supervisor]
Supervisor.start_link(children, opts)
end
enddefmodule MyAppWeb.Endpoint do
use Phoenix.Endpoint, otp_app: :my_app
# セッション設定
@session_options [
store: :cookie,
key: "_my_app_key",
signing_salt: "random_salt",
same_site: "Lax"
]
# 静的ファイル配信
plug Plug.Static,
at: "/",
from: :my_app,
gzip: false,
only: MyAppWeb.static_paths()
# ルーター
plug MyAppWeb.Router
end学習内容:
File.read/1、File.write/2を使ったI/O操作Path.join/2によるパス操作try/rescueによる例外処理- パターンマッチング
{:ok, content}と{:error, reason}
機能例:
- ファイル読み込み(priv/static/robots.txt)
- ファイル書き込み(任意のテキストファイル作成)
- エラーハンドリングの体験
学習内容:
Enumモジュールの活用(sum/1,max/1,min/1)- 数値変換と型安全性
- 再帰関数(フィボナッチ数列)
ArgumentError,ArithmeticErrorの例外処理
機能例:
- 数値の合計・平均・最大値・最小値計算
- フィボナッチ数列の計算
- 無効な入力に対するエラーハンドリング
学習内容:
Task.async/1、Task.await/2による並行処理Process.sleep/1を使った重い処理のシミュレーション- アクターモデルによる並行プログラミング
- HTMXを使った非同期通信
機能例:
- スリープ処理(1-10秒)
- CPU集約的計算タスク
- HTTP リクエストシミュレーション
- リアルタイムローディング表示
- Elixir 1.18+ - 関数型・並行プログラミング言語
- Phoenix Framework 1.7+ - Elixir製Webフレームワーク
- Bandit - 高性能HTTPサーバー
- Task & Process - 軽量並行処理
- HTMX - HTML拡張による動的UI(JavaScriptフレームワーク不要)
- Tailwind CSS - ユーティリティファーストCSS
- Phoenix LiveView - リアルタイム通信(今回は基本機能のみ)
- データベース不要 - 学習に集中するためDB設定を排除
- リアルタイム処理 - HTMXによる非同期通信
- エラーハンドリング - 実用的な例外処理パターン
- テストカバレッジ - 全機能のテストコード付き
learning_app/
├── lib/
│ ├── learning_app/
│ │ └── application.ex # アプリケーション起動設定
│ └── learning_app_web/
│ ├── controllers/
│ │ ├── learning_controller.ex # 学習機能のメインコントローラー
│ │ └── learning_html/ # HTMLテンプレート
│ │ ├── index.html.heex # メインページ
│ │ ├── file_operations.html.heex
│ │ ├── calculations.html.heex
│ │ └── async_operations.html.heex
│ ├── router.ex # ルーティング設定
│ └── endpoint.ex # HTTPエンドポイント
├── assets/
│ ├── js/
│ │ └── app.js # HTMX統合とJavaScript
│ └── css/
│ └── app.css # スタイル設定
├── config/ # 環境設定
├── test/ # テストコード
└── priv/static/ # 静的ファイル
cd learning_app
mix deps.getmix assets.setupmix assets.buildmix phx.serverhttp://localhost:4000 にアクセス後、「🎓 学習アプリ」ボタンをクリック
# 全テスト実行
mix test
# 特定のテストファイルのみ
mix test test/learning_app_web/controllers/learning_controller_test.exs- 関数型プログラミング - 不変性、パターンマッチング
- アクターモデル - 軽量プロセスによる並行処理
- エラーハンドリング - "Let it crash" 哲学と実用的例外処理
- パイプライン演算子 -
|>による関数合成
- MVC アーキテクチャ - Model-View-Controller パターン
- ルーティング - RESTful なURL設計
- テンプレート - HEExテンプレートエンジン
- 設定管理 - 環境別設定ファイル
- 非同期通信 -
hx-post,hx-target,hx-swap - プログレッシブエンハンスメント - HTML中心の開発
- ローディング表示 -
hx-indicator - イベントハンドリング - サーバーサイド処理
このプロジェクトでのHTMXライブラリの配置:
learning_app/
├── assets/
│ ├── js/
│ │ └── app.js # HTMX import & 初期化
│ ├── node_modules/
│ │ └── htmx.org/ # HTMX ライブラリ本体
│ │ └── dist/
│ │ ├── htmx.js # メインライブラリファイル
│ │ ├── htmx.esm.js # ES Module版
│ │ └── htmx.cjs.js # CommonJS版
│ └── package.json # npm依存関係(htmx.org)
└── lib/learning_app_web/
└── components/layouts/
└── root.html.heex # HTMXスクリプトの読み込み
<!-- フォーム送信時にPOSTリクエストを送信 -->
<form hx-post="/learning/perform-calculation"
hx-target="#result"
hx-swap="innerHTML">
<input name="operation" value="sum">
<input name="numbers" value="1,2,3,4,5">
<button type="submit">計算実行</button>
</form><!-- 結果を特定の要素に表示 -->
<div id="result">
<!-- ここに結果が表示される -->
</div><!-- 異なるswapオプション -->
<button hx-post="/api/data" hx-target="#content" hx-swap="innerHTML">
内容を置換 (デフォルト)
</button>
<button hx-post="/api/data" hx-target="#content" hx-swap="outerHTML">
要素ごと置換
</button>
<button hx-post="/api/data" hx-target="#content" hx-swap="beforeend">
末尾に追加
</button><!-- プリセット値付きボタン -->
<button hx-post="/learning/perform-calculation"
hx-vals='{"operation": "fibonacci", "numbers": "10"}'
hx-target="#result">
フィボナッチ計算
</button><!-- ローディングインジケーターの表示 -->
<button hx-post="/api/heavy-task"
hx-indicator="#loading">
重い処理を実行
</button>
<div id="loading" class="htmx-indicator">
処理中...
</div><!-- lib/learning_app_web/controllers/learning_html/calculations.html.heex -->
<form hx-post={~p"/learning/perform-calculation"}
hx-target="#calculation-result"
hx-swap="innerHTML">
<input type="hidden" name="_csrf_token" value={get_csrf_token()}>
<select name="operation">
<option value="sum">合計</option>
<option value="average">平均値</option>
<option value="fibonacci">フィボナッチ数列</option>
</select>
<input name="numbers" value="1.5, 2.7, 3.2, 4.8, 5.1">
<button type="submit" hx-indicator="#calc-loading">
計算を実行
</button>
</form>
<!-- ローディング表示 -->
<div id="calc-loading" class="htmx-indicator">
<div class="animate-spin">計算中...</div>
</div>
<!-- 結果表示エリア -->
<div id="calculation-result">
<!-- 計算結果がここに表示される -->
</div><!-- プリセット値での計算実行 -->
<button hx-post={~p"/learning/perform-calculation"}
hx-vals='{"operation": "sum", "numbers": "10, 20, 30, 40, 50", "_csrf_token": "#{get_csrf_token()}"}'
hx-target="#calculation-result"
hx-swap="innerHTML">
整数の合計計算
</button>// HTMX のインポートと初期化
import "htmx.org"
// CSRFトークンの自動送信設定
document.addEventListener("DOMContentLoaded", function() {
// HTMXリクエストにCSRFトークンを自動追加
document.body.addEventListener('htmx:configRequest', function(evt) {
const token = document.querySelector("meta[name='csrf-token']")?.getAttribute("content");
if (token) {
evt.detail.headers['x-csrf-token'] = token;
}
});
});<!-- フォーム内でのCSRFトークン -->
<input type="hidden" name="_csrf_token" value={get_csrf_token()}>
<!-- hx-vals でのCSRFトークン -->
<button hx-vals='{"_csrf_token": "#{get_csrf_token()}"}'>
ボタン
</button>- JavaScriptフレームワーク不要 - HTML属性だけで動的UI実現
- 軽量 - 約14KB(gzip圧縮時)
- プログレッシブエンハンスメント - 既存HTMLに段階的に機能追加
- サーバーサイド処理 - サーバーがHTMLを返すだけでSPA風の体験
- 学習コストが低い - HTML知識があれば簡単に習得可能
- 段階的学習: まず基本的な
hx-postとhx-targetから始める - 実践重視: 計算フォームやファイル操作で実際に動作を確認
- デバッグ: ブラウザの開発者ツールでネットワークタブを確認
- エラー対応: CSRFトークンやバリデーションエラーの処理方法を理解
# メイン設定ファイル - 全環境共通
config :learning_app, LearningAppWeb.Endpoint,
url: [host: "localhost"],
adapter: Bandit.PhoenixAdapter, # 高性能HTTPサーバー
# ...# 開発環境設定 - ライブリロード有効
config :learning_app, LearningAppWeb.Endpoint,
http: [ip: {0, 0, 0, 0}, port: 4000], # 全IPからアクセス可能
code_reloader: true, # ホットリロード
# ...# ルーティング設定
scope "/", LearningAppWeb do
pipe_through :browser
get "/learning", LearningController, :index
post "/learning/process-file", LearningController, :process_file
# ...
endtry do
# 危険な処理
File.read(file_path)
rescue
ArgumentError ->
# 引数エラーの処理
e ->
# その他のエラー
Logger.error("予期しないエラー: #{inspect(e)}")
endcase File.read(file_path) do
{:ok, content} ->
# 成功時の処理
{:error, reason} ->
# エラー時の処理
end
task = Task.async(fn ->
# 重い処理
Process.sleep(duration * 1000)
"処理完了"
end)
result = Task.await(task, 10_000) # 10秒でタイムアウト<!-- フォーム送信時に特定の要素を更新 -->
<form hx-post="/learning/process-file"
hx-target="#result"
hx-swap="innerHTML">
<!-- フォーム内容 -->
</form>
<div id="result">
<!-- 結果が表示される -->
</div>-
ポート4000が使用中
# 別のポートで起動 PORT=4001 mix phx.server -
アセットビルドエラー
# アセットの再セットアップ mix assets.setup mix assets.build -
依存関係エラー
# クリーンインストール mix deps.clean --all mix deps.get -
ファイル監視エラー
- Linux環境では
inotify-toolsが必要ですが、アプリの動作には影響しません
- Linux環境では
- 基本操作の理解 - まずは各ページを触って動作を確認
- コードリーディング -
learning_controller.exから読み始める - テストコード確認 - テストファイルで期待動作を理解
- 機能追加 - 新しい計算機能や非同期処理を追加
- エラー処理 - 意図的にエラーを発生させて挙動を確認
このプロジェクトは学習目的で作成されています。改善案やバグ報告は Issue や Pull Request でお寄せください。
Happy Learning with Elixir & Phoenix! 🎉


