LoginSignup
2
2

More than 5 years have passed since last update.

[Elixir+Trot] Trot-Frameworkを使って"Hello Trot!!"するだけの簡単なお仕事・・・

Last updated at Posted at 2015-06-17

目的

Trotフレームワークを利用しHello Trot!!を表示する。

実施環境

OS: Windows8.1
Erlang: Eshell V6.4 OTP v17.5
Elixir: v1.0.4
Trot Framework: v0.5

始める前に

Trotフレームワークを試してみます。

簡単にTrotの紹介をします。
Rubyで開発されたSinatraのような記述ができる、Elixir版のSinatraみたいなものです。
なので、ソースコード自体も少なくWebの勉強や書き捨てにちょうど良いと思います。
非常に小さいので、マイクロフレームワークと紹介されていました。

さて、説明はこんなところでやっていきましょう。

目次

  1. プロジェクト作成
  2. コンフィグ設定
  3. router作成
  4. まとめ

参考文献

1. プロジェクト作成

以下の通りプロジェクトを作成しました。

>cd プロジェクト作成ディレクトリ
>mix new trot_sample (以降、プロジェクト名はtrot_sampleとする)
>mix test

mix.exsを開き、以下の通り編集して下さい。

mix.exs
defmodule TrotSample.Mixfile do
  use Mix.Project

  def project do
    [app: :trot_sample,
     version: "0.0.1",
     elixir: "~> 1.0",
     build_embedded: Mix.env == :prod,
     start_permanent: Mix.env == :prod,
     deps: deps]
  end

  # Configuration for the OTP application
  #
  # Type `mix help compile.app` for more information
  def application do
    [applications: [:logger, :trot]]
  end

  # Dependencies can be Hex packages:
  #
  #   {:mydep, "~> 0.3.0"}
  #
  # Or git/path repositories:
  #
  #   {:mydep, git: "https://github.com/elixir-lang/mydep.git", tag: "0.1.0"}
  #
  # Type `mix help deps` for more examples and options
  defp deps do
    [
      {:trot, github: "hexedpackets/trot"}
    ]
  end
end

依存関係を解決します。

>mix deps.get
>mix deps.compile

2. コンフィグ設定

/config/config.exsを開き、以下の2行を追加して下さい。

config :trot, :port, 4000
config :trot, :router, TrotSample.Router

3. router作成

/libのディレクトリへ以下の名称でディレクトリを追加して下さい
ディレクトリ: trot_sample

/libにあったファイル(trot_sample.ex)は上記の作成したディレクトリへ移動して下さい。
また、以下のようにリネームして下さい。
リネーム: trot_sample.exrouter.ex

/lib/trot_sample/router.exを開き以下の通りソースコードを記述して下さい。

router.ex
defmodule TrotSample.Router do
  use Trot.Router

  get "/", do: 200

  get "/hello" do
    "Hello Trot!!"
  end

  import_routes Trot.NotFound
end

では、実行しましょう。
>iex -S mix

以下の二つのURLへアクセスしてみて下さい。
URL1: http://localhost:4000
結果1: 画面には何も表示されない。

URL2: http://localhost:4000/hello
結果2: テキストのみで"Hello Trot!!"と表示される。

また、コマンドプロンプトを確認してみるとログが出ています。

iex(1)>
18:59:41.065 [info]  GET /
iex(1)>
18:59:41.069 [info]  Sent 200 in 4ms
iex(1)>
18:59:46.036 [info]  GET /hello
iex(1)>
18:59:46.036 [info]  Sent 200 in 0ツオs

Tips:
configの設定を行わないと、
どんなページを開いてもデフォルトのNotFoundルータが、not foundと表示しています。

4. まとめ

これだけで実行できます。
簡単ですね!確かにSinatraっぽいです。

一応、レンダリングテンプレートを利用して表示する方法もやりましたので、
次の記事でアップしたいと思います。

余談なんですが、
Formの入力値を取得する方法とかがさっぱり分からないです。
どなたか知っている方がいましたらご教授頂けると嬉しいです~

以上で終わりです。

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2