はじめに
いまさらながらElixirとPhoenix触ってみました。「Railsに似ている」と噂されていますが使っているうちに「そんなの嘘だっ!」と何度もなりかけまして、イマイチ理解も進まなかったので、Rails と Phoenix を比較して理解を進めることにします。
今回はプロジェクトを立ち上げる際に使うコマンドをまとめていきます。
間違いなどありましたら指摘して頂ければと思います。
Elixirのいろは
とは言ってもまずはElixirについて知る必要がありましたので、下記サイトで一通り触ってみました。
elixir school
elixirの基礎を知れます。いろいろなサイトを見ましたが、これをやっておけばひとまず間違いないです。
Phoenix入門1 - Hello Phoenix
phoenixで静的ページを作成する所まで解説しています。
それでは、次からRailsとPhoenixの比較をしていきます。
rake と mix
mixはrailsで言うrakeとrails gなどの両方の役割を持っています。
プロジェクトを開始する
$ rails new project_name -d mysql
$ mix phoenix.new project_name -database mysql
コマンド確認
$ rake -T
$ mix -h
バージョン確認
$ rails -v
# => Rails 4.2.4
$ mix phoenix.new -v
# => Phoenix v1.1.4
DB
DB作成
$ vim config/database.yml
$ rake db:create
$ vim confg/config.exs
# config.exsはprod環境です。dev.exs, test.exsはそれぞれの環境を表しています。
$ mix ecto.create
テーブル作成
$ rails g migration create_users_table name:string email:string
# => db/migrate/2016xxxxx.rb
$ rails db:migrate
$ mix ecto.gen.migration create_users
# => priv/repo/migrations/2016xxxxx.exs
$ vim priv/repo/migrations/2016xxxx.exs
$ mix ecto.migrate
defmodule ChatPhoenix.Repo.Migrations.CreateUsers do
use Ecto.Migration
def change do
create table(:users) do
add :name, :string, size: 40
add :email, :string
timestamps
end
end
end
詳しくは: Ecto.Migration docs まで。
パッケージ管理
$ vim Gemfile
$ bundle install --path vendor/bundle
$ vim mix.exs
$ mix deps.get
...省略...
def application do
[mod: {ChatPhoenix, []},
applications: [:phoenix, :phoenix_html, :cowboy, :logger, :gettext,
:phoenix_ecto, :postgrex]]
end
...省略...
https://hex.pm/ からパッケージを探すことが出来ます。
Model作成
$ rails g model User name:string email:string --skip-migration
# => app/models/user.rb
$ mix phoenix.gen.model User users name:string email:string --no-migration
ページ作成
$ rails g controller users index
# => app/controllers/users_controller.rbとapp/views/users/index.html.erbを作成
$ mix phoenix.gen.html User users name:string email:string --no-migration --no-model
* creating web/controllers/user_controller.ex
* creating web/templates/user/edit.html.eex
* creating web/templates/user/form.html.eex
* creating web/templates/user/index.html.eex
* creating web/templates/user/new.html.eex
* creating web/templates/user/show.html.eex
* creating web/views/user_view.ex
* creating test/controllers/user_controller_test.exs
ルートの追加
Rails.application.routes.draw do
resources :users, only: :index
end
defmodule ChatPhoenix.Router do
use ChatPhoenix.Web, :router
...省略...
scope "/", ChatPhoenix do
pipe_through :browser # 上記の :browser の処理を行う
# "GET /"にアクセスすると、PageControllerのindexアクションが呼ばれる
resources "/users", UserController
end
end
所感
整理したら、アプリケーション作る時の最低限のコマンドやファイル配置はわかるようになりました。次はコントローラーやモデルの中身など詳細を比べてみようかと思います。
翻訳: 似て非なる Phoenix と Rails(原題『Phoenix is not Rails』)がPhoenixとRailsの違いをわかりやすくまとめています。良ければ読んでみてください。