LoginSignup
140
131

More than 5 years have passed since last update.

Elixirやるなら最初に知っておきたかったもの

Posted at

最近のElixir+Phoenixの流行り具合を見ていてちょっとやりたくなってみたくなりました。
んで、最初に目を通しておけばよかったなーと思ったことを纏めます。

最初にMixとiexの使い方を知っておけばよかった。

文法とか勉強する前に教えておいて欲しいです。
Mix:パッケージ管理ツールです。
iex:REPLってやつです。その場で打ち込んで動作確認できます

参考:http://moccosblue.blogspot.jp/2014/11/2014elixir10.html

参考ページを見ればわかりますが、

mix new study001

上記のように打ち込むとプロジェクトが作られて、依存ライブラリとかを取り込んでiexが使えるようになります。

* creating README.md
* creating .gitignore
* creating mix.exs
* creating config
* creating config/config.exs
* creating lib
* creating lib/study001.ex
* creating test
* creating test/test_helper.exs
* creating test/study001_test.exs

Your Mix project was created successfully.
You can use "mix" to compile it, test it, and more:

    cd study001
    mix test

Run "mix help" for more commands.

例えばhttpClientを動かして見たいとします。hex.pmからライブラリを見つけます。
https://hex.pm/packages/httpoison
見つけました
大抵githubのREADMEに使い方が書いてあります。

mix.exsを編集することで使いたいライブラリを取り込むことができます。

defmodule Study001.Mixfile do
  use Mix.Project

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

  def application do
    [applications: [:logger]]
  end

  defp deps do
     [{:httpoison, "~> 0.8.1"}] #<--編集箇所
  end
end

以下のコマンドで自動ダウンロードしてくれます。

mix deps.get

実行結果は省略

以下のコマンドでhttpoisonが使える状態でiexが立ち上がります。

iex -S mix

実際に使ってみます

tab補完が使えます

iex(6)> H<Tabを打つと対応するモジュール一覧が表示されます>
HTTPoison    HashDict     HashSet      Hex

更に関数一覧も見えます。
get!/3とかは引数3つ取るよってことです。!が付いているのは例外が起こる可能性がある関数です

iex(6)> HTTPoison.<Tab打ち込み>
AsyncChunk       AsyncEnd         AsyncHeaders     AsyncRedirect
AsyncResponse    AsyncStatus      Base             Error
Mixfile          Response         delete!/3        delete/3
get!/3           get/3            head!/3          head/3
options!/3       options/3        patch!/4         patch/4
post!/4          post/4           put!/4           put/4
request!/5       request/5        start/0

先頭にhを入れるとヘルプ表示されます。
h HTTPoisonと打つと使い方がわかります

iex(7)> h HTTPoison

                                   HTTPoison

The HTTP client for Elixir.

The HTTPoison module can be used to issue HTTP requests and parse HTTP
responses to arbitrary urls.

┃ iex> HTTPoison.get!("https://api.github.com")
┃ %HTTPoison.Response{status_code: 200,
┃                     headers: [{"content-type", "application/json"}],
┃                     body: "{...}"}

It's very common to use HTTPoison in order to wrap APIs, which is when the
HTTPoison.Base module shines. Visit the documentation for HTTPoison.Base for
more information.

Under the hood, the HTTPoison module just uses HTTPoison.Base (as described in
the documentation for HTTPoison.Base) without overriding any default function.

See request/5 for more details on how to issue HTTP requests

関数単位でも使えます

iex(6)> h HTTPoison.get!

                  def get!(url, headers \\ [], options \\ [])

Issues a GET request to the given url, raising an exception in case of failure.

If the request does not fail, the response is returned.

See request!/5 for more detailed information.

iex(7)>

実際に使ってみます

iex(9)> HTTPoison.get!("https://api.github.com")
%HTTPoison.Response{body: "{\"current_user_url\":\"https://api.github.com/user\",\"current_user_authorizations_html_url\":\"https://github.com/settings/connections/applications{/client_id}\",\"authorizations_url\":\"https://api.github.com/authorizations\",\"code_search_url\":\"https://api.github.com/search/code?q={query}{&page,per_page,sort,order}\",\"emails_url\":\"https://api.github.com/user/emails\",\"emojis_url\":\"https://api.github.com/emojis\",\"events_url\":\"https://api.github.com/events\",\"feeds_url\":\"https://api.github.com/feeds\",\"followers_url\":\"https://api.github.com/user/followers\",\"following_url\":\"https://api.github.com/user/following{/

//省略

出ますね。
自分でコードを書いてみたいとします。

コードはlib/study001.exに書きます。

study001/lib/study001.ex
defmodule Study001 do

    def hello do
        IO.puts "Hello"
    end

    def helloHttp do
        {:ok, response } = HTTPoison.get("https://api.github.com")
        response
    end
end

iexを終わらせず取り込む方法があります。

r Study001と打ち込みます

iex(17)> r Study001
lib/study001.ex:1: warning: redefining module Study001
{:reloaded, Study001, [Study001]}

実行できます

iex(18)> Study001.hello
Hello
:ok

iexを再起動せずにコードの修正後テストできるのは便利です。

 最初にここを見て勉強すればよかった

ElixirSchoolです。

参考:http://qiita.com/zero310/items/1adcaa19926d69771b85

をqiitaをあさって見つけました。
もうちょっとElixirで検索した時のヒット率が高ければいいのにと思いました

140
131
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
140
131