sinatra mongodb - rabbit slide show¨mongodb 今回はs inatraでm ongodbの 操作...

43
Sinatra MongoDB Sinatra MongoDB Powered by Rabbit 2.1.2 and COZMIXNG

Upload: hoangnhu

Post on 26-Jun-2018

225 views

Category:

Documents


0 download

TRANSCRIPT

Sinatra MongoDBSinatra

MongoDB

Powered by Rabbit 2.1.2 and COZMIXNG

SinatraとMongoDB今回はSinatraでMongoDBの操作を体験してみます。

進捗に合わせて、ドライバからRubyで使える便利なORMの紹介をします。

SinatraとMongoDBまずは初回なのでSinatraの基本からおさらいします。

Hello world

require 'sinatra'

get '/' do "Hello, world!"end

Hello worldこれは最も単純で有名な例ですが、HTTPヘッダを見てみましょう。

Hello worldブラウザにはこういったヘッダーの情報を確かめる機能が備わっています。

その中でも重要なのがRequest MethodがGETであるという点です。

HTTP MethodこれらのGETはHTTP Methodの一部で、主にGETやPOSTが使われています

GET POST PUT DELETE

OPTION

何か見せる

何か生成する

何か更新する

何か削除する

何か満たす

http://www.sinatrarb.com/intro-ja.html より引用

POSTでは、次にpostメソッドを試してみましょう

require 'sinatra'

post '/' do "Hello world!"end

POST

$ curl -X POST http://localhost:4567

POSTコマンドを送信する方法。

POST

require 'sinatra'

post '/' do "Hello world!"end

get '/' do erb <<EOF <form method='post' action='/'> <input type='submit' /> </form>EOFend

POSTただし、POSTコマンドは通常では値の取得には用いません

値を取得するときにはGETを使います

MongoDBそれでは実際にデータを保存するためにMongoDBを利用しましょう。

MongoDBインストールは行ってきましたか?

$ which mongo$ which mongod

MongoDBまずは基本から。

$ mongo # クライアントの起動> db # 現在のテーブル> use foo # foo をこれから使用(この時点ではまだ書き込まれていない)> db # foo

MongoDB外部接続の場合。

$ mongo <hostname>:<port>/<table> -u <user> -p <password>

MongoDBまずは基本から。

> a = { name: 'Frank' }> db.sinatraDB.insert(a) # 挿入> show collections # sinatraDBが書き込まれている> db.sinatraDB.find() # 検索

MongoDB

$ gem install mongo bson_ext

bson_extはmongoライブラリにBSON形式をサポートさせるためのGemです

MongoDB

require 'sinatra'require 'mongo'

include Mongo # Mongoの省略

configure do conn = MongoClient.new # localhost:27017 set connection: conn set db: conn.db('foo') # use fooend

get '/collections' do settings.db.collection_names.to_a.to_s # show collections と同じend

MongoDB

require 'sinatra'require 'mongo'

get '/' do # ドキュメント全体 settings.db['sinatraDB'].find.to_a.to_send

get '/:collection' do |col| # name が collectionであるものをひとつ返す settings.db['sinatraDB'].find_one(name: col).to_send

Hamlテンプレートエンジンを使います

$ gem install haml

Hamlテンプレートエンジンを使います

get '/' do haml :indexend

Haml./views/index.haml

%form{action: '/', method: 'post'} %input{name: 'name', placeholder: 'name'} %input{type: 'submit'}

注意:インデント幅はソフトスペース”2”です

MongoDBSinatraからデータを登録します

post '/' do bson_id = settings.db['sinatraDB'].insert(params) bson_id.to_send

このIDをコピーしてください

MongoDBBSON_IDからの検索?

get '/id/:id' do |id| settings.db['sinatraDB'].find(id).to_send

MongoDBBSON_IDからの検索

get '/id/:id' do |id| id = BSON::ObjectId.from_string(id) settings.db['sinatraDB'].find(id).to_send

ヘルパー

helpers do def foo 'baz' endend

ヘルパー

または

module Foo def foo 'baz' endend

helpers Foo

ヘルパー

# Haml, Slim= foo

# ERB<%= foo %>

ヘルパー

helpers do def find_by_name(name) settings.db['sinatraDB'].find(name: name) end

def find_all settings.db['sinatraDB'].find endend

ヘルパー

= find_by_name.count

%ul - find_by_name('Frank').each do |document| %li= document['_id']

データの更新

./views/index.haml

%ul - find_all.each do |document| %li %a{href: "/update/#{document['_id']}"}= document['name']

データの更新

ルーティング

get '/update/:id' do |id| @id = id haml :updateend

データの更新

./views/update.haml

%h1= find_by_id(@id)

%form{action: "/update/#{@id}", method: 'post'} %input{name: 'name', value: find_by_id(@id)} %input{type: 'submit'}

データの更新

ヘルパー

helpers do def find_by_id(id) id = BSON::ObjectId.from_string(id) settings.db['sinatraDB'].find_one(id)['name'] endend

データの更新

post '/update/:id' do |id| id = BSON::ObjectId.from_string(id) settings.db['sinatraDB'].update({_id: id}, params) redirect '/'end

データの削除

./views/index.haml

%ul - find_all.each do |document| %li = document['name'] | %a{href: "/update/#{document['_id']}"} 更新 | %a{href: "/delete/#{document['_id']}"} 削除

データの削除

ルーティング

get '/delete/:id' do |id| id = BSON::ObjectId.from_string(id) settings.db['sinatraDB'].remove(_id: id) redirect '/'end

本来はPOSTを使うのですが、今回は操作感を重視してGETを使います

データの追加

はじめに追加した部分もredirectに書き換えましょう

post '/' do settings.db['sinatraDB'].insert(params) redirect '/'end

未完了と完了

ようやくToDoリストを作り始める基礎をおさえることができました。

今度はそれぞれのタスクが完了しているかどうかを判断させます。

未完了と完了

./views/index.haml

%ul - find_all.each do |document| %li - if document['status'] %s= document['name'] | %a{href: "/delete/#{document['_id']}"} 削除 - else = document['name'] | %a{href: "/done/#{document['_id']}"} 完了 | %a{href: "/update/#{document['_id']}"} 更新 | %a{href: "/delete/#{document['_id']}"} 削除

未完了と完了

= document['status'].class.to_s#=> NilClass

nil(空白)が返ってくるのでエラーにならない

あとから値を変更するのが容易

未完了と完了

ルーティング

get '/done/:id' do |id| id = BSON::ObjectId.from_string(id) settings.db['sinatraDB'].update( {_id: id}, { "$set" => {status: Time.now} } ) redirect '/'end

以上

今回はとても単純なToDoリストを作成してみました

次回以降はAjaxを絡めて、もっと高機能なアプリケーションを作成しましょう

Powered by Rabbit 2.1.2 and COZMIXNG