Más contenido relacionado La actualidad más candente (20) Similar a 20090418 イケテルRails勉強会 第1部Rails編 (20) 20090418 イケテルRails勉強会 第1部Rails編2. 1部での目的
• ActiveResource という機能をつかって 食べログをはじめとした
WebAPI を使えるようになろう!!
• paperclip プラグインを使ってファイルの添付を出来るようになろう!!
• AIR と連携をしてみよう!!
• 習うよりとにかく慣れてみよう!!
Don’t think, feel.
(考えるな、感じるんだ。)
2
3. 1部でやること
Ruby on Rails のプロジェクトを作成
1.
ActiveResource をつかって食べログAPIを表示する
2.
食べログの画面に検索条件を追加する
3.
レストランに1行メモを追加できるようにする
4.
paperclip を使って画像を添付できるようにする
5.
AIR との連携の準備をする
6.
3
5. 1.Ruby on Rails のプロジェクトを作成
その前に環境の確認
• まずは Rubyのバージョンを確認しましょう。
>ruby -v
ruby 1.8.6 (2008-08-11 patchlevel 287) [i386-mswin32]
• Rails のバージョンは 2.3.2
>rails -v
Rails 2.3.2
• DBはSQLite3 を使用します
>sqlite3 --version
3.6.11
• RailsとSQLite3を接続する sqlite3-rubyは必須
>gem install sqlite3-ruby --version 1.2.3
>gem list sqlite3-ruby ←(Windowsの場合)
>gem list --local | grep sqlite3-ruby ←(Macの場合)
sqlite3-ruby (1.2.3)
5
6. 1.Ruby on Rails のプロジェクトを作成
今回の勉強会では
C:¥rbcフォルダで作業している事を前提に説明します。
Cドライブ直下にrbcフォルダを作成してください。
6
7. 1.Ruby on Rails のプロジェクトを作成
それでは、さっそくRailsプロジェクトを作成しましょう。
以下のコマンドを入力してください。
C:¥Users¥***>cd c:¥rbc
“rails” コマンドでRailsのプロジェクトを作成
“-d” で使用するDBを指定する
c:¥rbc>rails rbc_tabelog -d sqlite3
create
create app/controllers
create app/helpers
(省略)
create log/production.log
create log/development.log
create log/test.log
これでRailsのプロジェクトの作成は完了です。
7
9. 1.Ruby on Rails のプロジェクトを作成
ついでにデータベースも作成
以下のコマンドを入力しましょう
c:¥rbc>cd rbc_tabelog
c:¥rbc¥rbc_tabelog>rake db:create
(in c:/rbc/rbc_tabelog)
“rake db:create” コマンドでデータベースを作成します。
C:¥rbc¥rbc_tabelog¥db フォルダに
development.sqlite3 というファイルができていればオッケー!
コマンドに失敗した場合、rbc_tabelog¥config¥database.yml を編集してください
参考: ¥1部資料¥Chap_1¥rbc_tabelog¥config¥database.yml
9
10. 1.Ruby on Rails のプロジェクトを作成
サーバの起動
c:¥rbc¥rbc_tabelog>ruby script/server
=> Booting Mongrel
=> Rails 2.3.2 application starting on http://0.0.0.0:3000
=> Call with -d to detach
=> Ctrl-C to shutdown server
“ruby script/server” コマンドでサーバを起動します
サーバが実行できたらブラウザで以下のURLを実行してみましょう。
http://localhost:3000
10
12. 1.Ruby on Rails のプロジェクトを作成
2部に進む前にちょっとだけRailsについて説明
Rails は MVC というパターンによって設計、実装していきます。
Model(モデル)・・・データを格納する部分、DBから取り出したデータを保持する
・Railsでは、「app¥models¥基本名(単数形).rb」
・NetBeansでは「モデル¥基本名.rb」で表示されます
View(ビュー)・・・ユーザに向けた見た目(画面表示)部分。ユーザーインターフェース
・Railsでは、「app¥views¥基本名(複数形)¥画面名.html.erb」
・NetBeansでは「ビュー¥基本名(複数形)¥画面名.html.erb 」
Controller(コントローラ)・・・ユーザからの入力を処理する部分。
・Railsでは、「app¥views¥基本名(複数形)_controller.rb」
・NetBeansでは「コントローラ¥基本名(複数形) _controller.rb 」
12
17. 2.ActiveResource をつかって食べログAPIを表示する
rbc_tabelog/app/models/restaurant.rb をさらに変更
class Restaurant < ActiveResource::Base
API の URL を設定
self.site = quot;http://api.tabelog.com/quot;
def self.find_restaurants(restautant_params = {})
restautant_params[:Key] = quot;96448b290b6556976f047110914fcf91e88c38b9quot;
Hash.from_xml(
self.find( 食べログAPIのキーを設定します。
:one, ご自分のキーを持っている方は、こちらに入力
:from => quot;/Ver2.1/RestaurantSearch/quot;,
:params => restautant_params
検索メソッドを作成
).to_xml
今回は引数をハッシュで渡します
)
end
Hash.from_xmlでxmlをハッシュに(無理矢理)変換しています。
end
これで model は完成!
17
19. 2.ActiveResource をつかって食べログAPIを表示する
続いて rbc_tabelog/app/views/restaurants/index.html.erb の修正
ココはこんな感じでごっそり置き換えましょう
ActiveResouece から値を取得します。
<h1>RBC食べログ</h1>
<ul>
<% @restaurants[quot;itemquot;].each do |item| -%>
<li>
<%= link_to item[quot;restaurant_namequot;],
item[quot;tabelog_urlquot;], {:target => '_blank'} %>
</li>
<% end -%>
</ul> 食べログAPI結果
<RestaurantInfo>
<Item>
<RestaurantName>千松しま</RestaurantName>
<TabelogUrl>http://r.tabelog.com/miyagi/A0404/A040404/4001636/</TabelogUrl>
<TotalScore>4.67</TotalScore>
<TasteScore>4.64</TasteScore>
<ServiceScore>4.69</ServiceScore>
<MoodScore>4.32</MoodScore>
<Situation>友人・同僚と、デート、接待</Situation>
<DinnerPrice>¥10,000 ~¥14,999</DinnerPrice>
<LunchPrice>¥10,000 ~¥14,999</LunchPrice>
<Category>割烹・小料理</Category>
<Station>東塩釜、本塩釜、西塩釜</Station>
</Item>
19
・・・
29. 3.食べログの画面に検索条件を追加する
続いてrbc_tabelog/app/views/restaurants/index.html.erb の修正
赤字部分を追記していきます
<h1>RBC食べログ</h1>
<% form_tag({}, {:multipart => true} ) do -%>
<p>
都道府県:<%= select_tag :prefecture,
options_from_collection_for_select(@prefectures, :en, :ja, params[:prefecture]) %>
</p>
<p>
ページ:<%= select_tag :pageNum, options_for_select(@pages, params[:pageNum].to_i) %>
</p>
<%= submit_tag quot;検索quot;, {:name => quot;searchquot;} %>
<hr />
<ul>
<% @restaurants[“itemquot;].each do |item| -%>
<li>
<%= link_to item[“restaurant_namequot;],
item[“tabelog_urlquot;], {:target => '_blank'} %>
</li>
<% end -%>
</ul>
<% end -%>
最後の “end” も忘れずに!!
29
37. 4.レストランに1行メモを追加できるようにする
http://localhost:3000/restaurants
では画面を確認してみましょう
メモ欄が追加されていますか?
登録してみてください。
結果が各レストラン横に追加されるのを確認できます。
37
40. 5.paperclip を使って画像をアップできるようにする
さっそく paprtclip プラグインをインストールしましょう
paperclip プラグインは git を使って入手できますが、
最新版はなぜか Windows 環境では動きません…。
ちなみに git コマンドで入手する場合は以下のようにすればOKです(git 必須)
ruby script/plugin install git://github.com/thoughtbot/paperclip.git
なので古いバージョン 2.2.2 を使います。
資料の中に プラグイン本体を準備しています。
「¥1部資料¥_paperclipプラグイン¥paperclip」
ベンダー/plugins にドラッグオンドロップしましょう
rbc_tabelog¥vendor¥plugins にコピーしてもいいです。
40
42. 5.paperclip を使って画像をアップできるようにする
ちなみに先ほどのコマンドを実行する事で、
Bookmarks テーブルに 画像を保存するためのマイグレーションファイルが追加されました。
rbc_tabelog/db/migrate/数字_add_attachments_photo_to_bookmark.rb
class AddAttachmentsPhotoToBookmark < ActiveRecord::Migration
def self.up
add_column :bookmarks, :photo_file_name, :string
add_column :bookmarks, :photo_content_type, :string
add_column :bookmarks, :photo_file_size, :integer
end
def self.down
remove_column :bookmarks, :photo_file_name
remove_column :bookmarks, :photo_content_type
remove_column :bookmarks, :photo_file_size
end
end
42
46. 5.paperclip を使って画像をアップできるようにする
rbc_tabelog/app/controllers/restaurants_controller.rb
index メソッドの中の赤字部分を追加して登録したデータを取得できるようにします
def index
@prefectures = Prefecture.find(:all)
@pages = Array.new(100){|i| i+1}
@restaurants = Restaurant.find_restaurants(request.query_parameters)[quot;restaurantquot;]
@restaurants[quot;itemquot;].each do |item|
bookmark = Bookmark.find_by_rcditem[“tabelog_rcdquot;]
if bookmark
item[quot;memoquot;] = bookmark.memo
item[quot;image_urlquot;] = bookmark.photo_file_name ? bookmark.photo.url : nil
end
end
“.url” でアップしたファイルのURL を取得できる
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @restaurants }
end
end
46
51. 6. AIR との連携の準備をする
ただ、AIRとの連携で以下の問題があります。
・同じタグ名が重なると同じく処理が面倒
・paperclip で追加した画像のURLが相対URLである
・タグ名にハイフンが含まれているとAIR側の処理が面倒
“Item”タグが下の階層にもあってそれが面倒
<hash> そもそも array のタグが 単数系なのも個人的に気持ち悪い
<num-of-result>10483</num-of-result>
<item type=quot;arrayquot;>
<item>
<image-url>/photos/1/original/100x100_233565.jpg</image-url>
<tabelog-mobile-url>
画像のURLがhttpから始まっていない
http://m.tabelog.com/hokkaido/A0101/A010105/1000049/
</tabelog-mobile-url>
<category>フレンチ</category>
タグ名にハイフンが含まれている
51
52. 6. AIR との連携の準備をする
さっそく問題を解決しましょう
・同じタグ名が重なると同じく処理が面倒、
・paperclip で追加した画像のURLが相対URLである
・要素の名前にハイフンが含まれているとAIR側の処理が面倒
赤字部分を変更、追記してください。
rbc_tabelog/app/controller/restaurant_controller.rb
def index
@prefectures = Prefecture.find(:all)
@pages = Array.new(100){|i| i+1}
@restaurants = Restaurant.find_restaurants(request.query_parameters)[“restaurantquot;]
@restaurants[“itemquot;].each do |item|
bookmark = Bookmark.find_by_url item[“tabelog_urlquot;]
画像のURLにhttp://~を追加します
if bookmark
item.attributes[“memoquot;] = bookmark.memo
item.attributes[“image_urlquot;] = bookmark.photo_file_name ? request.protocol + request.host_with_port +
bookmark.photo.url : nil
end
“item”→”items”に変更
end
@restaurants[quot;itemsquot;] = @restaurants[quot;itemquot;]
@restaurants.delete quot;itemquot;
root オプションでxml の先頭タグ名を変更できます
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @restaurants.to_xml(:root => quot;restaurantquot;, :dasherize => false) }
end 52
dasherizeオプションfalseでアンスコをハイフンに変換しなくなります
end
53. 6. AIR との連携の準備をする
このままだと、画面が動かなくなっちゃうので画面もちょっと修正。
ビュー/restaurants/index.html.erb
<h1>RBC食べログ</h1>
<% form_tag({:action => quot;indexquot;}, {:multipart => true}) do -%>
・・・(省略)・・・
<hr />
<ul>
<% @restaurants[quot;itemsquot;].each do |item| -%>
<li>
<%= radio_button_tag :url, item[quot;tabelog_urlquot;] %>
<%= link_to item[quot;restaurant_namequot;],
item[quot;tabelog_urlquot;], {:target => '_blank'} %>
<%= item[quot;memoquot;] %>
<% unless item[quot;image_urlquot;].blank? -%>
<br /><%= image_tag item[quot;image_urlquot;] %>
<% end -%>
</li>
<% end -%>
</ul>
・・・(省略)・・・
<% end -%>
53
54. 6. AIR との連携の準備をする
これで以下の問題の対応が完了しました
・同じタグ名が重なると同じく処理が面倒
・paperclip で追加した画像のURLが相対URLである
ついでに先頭タグを”restaurant” に変更してみました
<restaurant>
<items type=quot;arrayquot;>
このタグ名が “Item” → “Items” に変わりました
<item>
<image_url>
http://localhost:3000/photos/1/original/100x100_233565.jpg
</image_url>
<tabelog_mobile_url>
http://m.tabelog.com/hokkaido/A0101/A010105/1000049/
“http://” から始まるURLになりました
</tabelog_mobile_url>
<category>フレンチ</category>
タグ名がアンスコ区切りに戻りました
54