LoginSignup
4
2

More than 5 years have passed since last update.

日めくりPhoenix、毎日Elixir

Last updated at Posted at 2019-02-09

日めくりPhoenix、毎日Elixir

・はじめに

1億2千万人のmixファンの皆さん!今日も元気にiexしてますか?

最近マンネリなあなたのために日替わりでelixirネタを表示するwebアプリ「日めくりPhoenix、毎日Elixir」(通称:evrylixir)の実装にチャレンジしてみます!

・開発環境

PC Mac Book Pro (Retina, 13-inch, Late 2013)
OS Mojave
Memory 8GB
言語 elixir v1.7
FW Phoenix 1.3

参考サイト

mix phx.gen.jsonを使わずとも気軽に作れるElixir/Phoenix API

前提条件

  • Google Custom Search APIを有効化しAPIキーを取得済みであること。
  • Custom Search Engineの検索エンジンIDを取得済みであること。

実装

コンソールから以下のコマンドを入力しPhoenixの初期画面の表示まで行います。

>mix phx.new evrylixir --no-ecto
>iex -S mix phx.server

fig01.PNG

下記のファイルを追加し、コードを記述します。

lib/evrylixir_web/controllers/json_controller.ex
defmodule EvrylixirWeb.JsonController do
  use EvrylixirWeb, :controller

  def getUrls(conn, param)do
    render(conn,"api.json",%{api_data: param})
  end
end
lib/evrylixir_web/viewss/json_view.ex
defmodule EvrylixirWeb.JsonView do
  use EvrylixirWeb, :view

  def render("api.json",%{api_data: _})do
    url = Scraper.randomScrape("elixir")
    %{
      url: url
    }
  end
end
lib/scraper.ex

defmodule Scraper do

  def randomScrape(keyword) do
    HTTPoison.get!("https://www.googleapis.com/customsearch/v1?key=APIキー&cx=検索エンジンID&q=" <> keyword)
    |>body
    |>Poison.decode!
    |>items
    |>Enum.map(fn(%{"link"=>link}) -> link end)
    |>Enum.random
  end
  def body(%{status_code: 200,body: json_body}) do
   json_body
  end
  def items(%{"items"=>items}) do
    items
  end

end

以下のファイルにコードを追記します。

lib/evrylixir_web/router.ex

  ...省略...

  scope "/", EvrylixirWeb do
    pipe_through :browser # Use the default browser stack

    get "/", PageController, :index

    get "/api", JsonController, :getUrls
  end
lib/evrylixir_web/templates/page/index.html.eex
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.min.js"></script>

<div id="app" class = "row">
<iframe :src="jsons.url" width="100%" height="600px" ></iframe>
</div>


<script>
var app = new Vue({
  el: '#app',
  data:
  {
    jsons:[]
  },
  mounted(){
    axios.get('/api').then(response=>{this.jsons=response.data})
  }
})
</script>
mix.exs

defp deps do
    [
      ...省略...

      {:poison, "~> 3.1.0"},
      {:httpoison, "~> 0.9.0"}
    ]
end

実装はここまでです。

テスト

動作確認を行います。

>mix phx.server

fig02.png

え!?

(゚ロ゚;)

続く!!

4
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
4
2