Skip to content
tommykey0925Public

About

elixir

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

8 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 

Repository files navigation

🎓 Elixir & Phoenix 学習アプリ

Elixir言語とPhoenix Frameworkを使った実用的なプログラミング学習アプリケーションです。HTMXを活用してモダンな非同期Webアプリケーションの構築方法を体験できます。

プレビュー

📖 Elixirの基本文法

基本データ型

# 整数と浮動小数点
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()               # 24

Enumモジュール

list = [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 Frameworkの基本

MVCアーキテクチャ

Phoenix は Model-View-Controller パターンを採用:

  • Model: データとビジネスロジック(Ecto スキーマ)
  • View: データの表示とテンプレート(HTML、JSON)
  • Controller: リクエスト処理とレスポンス生成

基本的な Phoenix コントローラー

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

HEEx テンプレート

# 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>

📁 Phoenix プロジェクトの基本ファイル構成

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

重要なファイルの役割

mix.exs - プロジェクト設定

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
end

lib/my_app/application.ex - アプリケーション起動

defmodule 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
end

lib/my_app_web/endpoint.ex - HTTPエンドポイント

defmodule 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

🚀 提供機能

1. ファイル操作の学習 (/learning/file-operations)

学習内容:

  • File.read/1、File.write/2を使ったI/O操作
  • Path.join/2によるパス操作
  • try/rescueによる例外処理
  • パターンマッチング {:ok, content} と {:error, reason}

機能例:

  • ファイル読み込み(priv/static/robots.txt)
  • ファイル書き込み(任意のテキストファイル作成)
  • エラーハンドリングの体験

2. 計算処理の学習 (/learning/calculations)

学習内容:

  • Enumモジュールの活用(sum/1, max/1, min/1)
  • 数値変換と型安全性
  • 再帰関数(フィボナッチ数列)
  • ArgumentError, ArithmeticErrorの例外処理

機能例:

  • 数値の合計・平均・最大値・最小値計算
  • フィボナッチ数列の計算
  • 無効な入力に対するエラーハンドリング

3. 非同期処理の学習 (/learning/async-operations)

学習内容:

  • 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/                        # 静的ファイル

🏃‍♂️ 起動方法

1. 依存関係のインストール

cd learning_app
mix deps.get

2. アセットのセットアップ

mix assets.setup

3. アセットのビルド

mix assets.build

4. サーバー起動

mix phx.server

5. ブラウザでアクセス

http://localhost:4000 にアクセス後、「🎓 学習アプリ」ボタンをクリック

🧪 テスト実行

# 全テスト実行
mix test

# 特定のテストファイルのみ
mix test test/learning_app_web/controllers/learning_controller_test.exs

📚 学習ポイント

Elixirの基本概念

  1. 関数型プログラミング - 不変性、パターンマッチング
  2. アクターモデル - 軽量プロセスによる並行処理
  3. エラーハンドリング - "Let it crash" 哲学と実用的例外処理
  4. パイプライン演算子 - |> による関数合成

Phoenixフレームワーク

  1. MVC アーキテクチャ - Model-View-Controller パターン
  2. ルーティング - RESTful なURL設計
  3. テンプレート - HEExテンプレートエンジン
  4. 設定管理 - 環境別設定ファイル

HTMXによるモダンWeb開発

  1. 非同期通信 - hx-post, hx-target, hx-swap
  2. プログレッシブエンハンスメント - HTML中心の開発
  3. ローディング表示 - hx-indicator
  4. イベントハンドリング - サーバーサイド処理

🌐 HTMX の基本的な使い方

HTMXの設置場所

このプロジェクトでの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スクリプトの読み込み

基本的なHTMX属性

1. hx-post - POSTリクエストの送信

<!-- フォーム送信時に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>

2. hx-target - 結果の表示先指定

<!-- 結果を特定の要素に表示 -->
<div id="result">
  <!-- ここに結果が表示される -->
</div>

3. hx-swap - 内容の更新方法

<!-- 異なる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>

4. hx-vals - 追加データの送信

<!-- プリセット値付きボタン -->
<button hx-post="/learning/perform-calculation"
        hx-vals='{"operation": "fibonacci", "numbers": "10"}'
        hx-target="#result">
  フィボナッチ計算
</button>

5. hx-indicator - ローディング表示

<!-- ローディングインジケーターの表示 -->
<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の設定とCSRF対応

アプリケーション初期化(assets/js/app.js)

// 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 トークンの埋め込み

<!-- フォーム内でのCSRFトークン -->
<input type="hidden" name="_csrf_token" value={get_csrf_token()}>

<!-- hx-vals でのCSRFトークン -->
<button hx-vals='{"_csrf_token": "#{get_csrf_token()}"}'>
  ボタン
</button>

HTMXの利点

  1. JavaScriptフレームワーク不要 - HTML属性だけで動的UI実現
  2. 軽量 - 約14KB(gzip圧縮時)
  3. プログレッシブエンハンスメント - 既存HTMLに段階的に機能追加
  4. サーバーサイド処理 - サーバーがHTMLを返すだけでSPA風の体験
  5. 学習コストが低い - HTML知識があれば簡単に習得可能

学習のポイント

  • 段階的学習: まず基本的な hx-post と hx-target から始める
  • 実践重視: 計算フォームやファイル操作で実際に動作を確認
  • デバッグ: ブラウザの開発者ツールでネットワークタブを確認
  • エラー対応: CSRFトークンやバリデーションエラーの処理方法を理解

🔧 設定ファイルの解説

config/config.exs

# メイン設定ファイル - 全環境共通
config :learning_app, LearningAppWeb.Endpoint,
  url: [host: "localhost"],
  adapter: Bandit.PhoenixAdapter,  # 高性能HTTPサーバー
  # ...

config/dev.exs

# 開発環境設定 - ライブリロード有効
config :learning_app, LearningAppWeb.Endpoint,
  http: [ip: {0, 0, 0, 0}, port: 4000],  # 全IPからアクセス可能
  code_reloader: true,                   # ホットリロード
  # ...

lib/learning_app_web/router.ex

# ルーティング設定
scope "/", LearningAppWeb do
  pipe_through :browser
  
  get "/learning", LearningController, :index
  post "/learning/process-file", LearningController, :process_file
  # ...
end

💡 実装のポイント

1. エラーハンドリングパターン

try do
  # 危険な処理
  File.read(file_path)
rescue
  ArgumentError -> 
    # 引数エラーの処理
  e -> 
    # その他のエラー
    Logger.error("予期しないエラー: #{inspect(e)}")
end

2. パターンマッチングの活用

case File.read(file_path) do
  {:ok, content} -> 
    # 成功時の処理
  {:error, reason} -> 
    # エラー時の処理
end

3. 並行処理の実装

task = Task.async(fn ->
  # 重い処理
  Process.sleep(duration * 1000)
  "処理完了"
end)

result = Task.await(task, 10_000)  # 10秒でタイムアウト

4. HTMXとの連携

<!-- フォーム送信時に特定の要素を更新 -->
<form hx-post="/learning/process-file" 
      hx-target="#result" 
      hx-swap="innerHTML">
  <!-- フォーム内容 -->
</form>

<div id="result">
  <!-- 結果が表示される -->
</div>

🐛 トラブルシューティング

よくある問題と解決方法

  1. ポート4000が使用中

    # 別のポートで起動
    PORT=4001 mix phx.server
  2. アセットビルドエラー

    # アセットの再セットアップ
    mix assets.setup
    mix assets.build
  3. 依存関係エラー

    # クリーンインストール
    mix deps.clean --all
    mix deps.get
  4. ファイル監視エラー

    • Linux環境ではinotify-toolsが必要ですが、アプリの動作には影響しません

🎯 学習の進め方

  1. 基本操作の理解 - まずは各ページを触って動作を確認
  2. コードリーディング - learning_controller.exから読み始める
  3. テストコード確認 - テストファイルで期待動作を理解
  4. 機能追加 - 新しい計算機能や非同期処理を追加
  5. エラー処理 - 意図的にエラーを発生させて挙動を確認

🔗 参考リソース


🤝 コントリビューション

このプロジェクトは学習目的で作成されています。改善案やバグ報告は Issue や Pull Request でお寄せください。

Happy Learning with Elixir & Phoenix! 🎉

About

elixir

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages