light tableでclojure入門#2
DESCRIPTION
ClojureでLight Tableを使い、ウェブアプリケーションを作ります。Tokyo.clj#20で使用した資料です。TRANSCRIPT
Light Table でClojure 入門ニャンパス 登尾 (@tnoborio)
http://bit.ly/hello-clojure2
やること
前回まで : http://bit.ly/hello-clojure1
Light Table の使い方のおさらい
Ringウェブアプリケーション
Light Table の使い方
Workspace Commands
Workspace の表示● Control + Space で Commands● Commands を出して、“ Toggle workspace
tree” を選択→ Workspace が左ペインに表示
Mac で、 Control+Space が動かない場合、システム環境設定 >Spotlight“Spotlight メニューのキーボードショートカットチェック”を外す
Light Table で REPL
Commands から” Instarepl: Open a clojure instarepl”
● (+ 1 2 3)● (println “Hello”)標準出力は、Commands→“Console: Toggle console”
Leiningen$ lein -versionLeiningen 2.3.4
( 入ってなければ )Leiningen のインストール前回を参考に http://bit.ly/hello-clojure1
ウェブアプリケーション
テンプレートを使ったプロジェクト作成
lein new compojure webapp
Light Table から
1.View メニュー→ Workspace を表示2.Commands→”Add folder” で
Workspace に webapp を追加
ディレクトリ構造
● project.clj● src/webapp/handler.clj● resouces/public/● test/
起動
$ cd webapp$ lein ring serverブラウザが立ち上がり、“ Hello World” と表示されれば OK
project.clj
(defproject webapp "0.1.0-SNAPSHOT" :description "FIXME: write description" :url "http://example.com/FIXME" :dependencies [[org.clojure/clojure "1.5.1"] [compojure "1.1.6"]] :plugins [[lein-ring "0.8.10"]] ← Leiningen の Ring プラグイン :ring {:handler webapp.handler/app} :profiles {:dev {:dependencies [[javax.servlet/servlet-api "2.5"] [ring-mock "0.1.5"]]}})
src/webapp/handler.clj
(ns webapp.handler (:use compojure.core) (:require [compojure.handler :as handler] [compojure.route :as route]))
(defroutes app-routes (GET "/" [] "Hello World. hogehoge") ← 書き換えて保存しブラウザから確認 (route/resources "/") (route/not-found "Not Found"))(def app (handler/site app-routes))
例 ) HTML ページを追加(defroutes app-routes (GET "/" [] "Hello World. hogehoge") (GET "/hoge.html" [] "<html><body>hoge</body></html>") (route/resources "/") (route/not-found "Not Found"))
例 ) 画像や css ファイルを置く
・ resouces/public ディレクトリのファイルを置くとそのまま表示。
resouces/public/nyampass.jpg→ http://localhost:3000/nyampass.jpg
handler.clj のここのおかげ (route/resources "/")
例 ) GET 、 POST の値
(defroutes app-routes ... (GET "/params" {params :params} (str params)) …)
http://localhost:3000/params?a=hoge&b=1234
→ {:b "1234", :a "hoge"}
例 ) Redirect
マップとして返す (GET "/redirect" [] {:status 302 :headers {"Location" "http://www.yahoo.com/"} :body ""})