AResTサービス
ActiveResource CompaTible な RESTful API を考える。「Railsレシピブック 183の技」を参考に。
ちょいと必要があって、既存DB(テーブル)への参照のみの AResTサービスを作る、テーブル一つ分だけの。
- Railsアプリケーション作成
- 下準備
- script\generate cucumber
- script\generate spec
- databese.yml
- 取り敢えず developmentのデータベースコネクション定義を所要の既存DB向けのものに
- script\generate rspec_scaffold <適当なモデル名> (大文字小文字単数形注意)
- DB定義
- マイグレートファイル削除
- rake db:migrate
- 何も起きない
- モデル定義部分にてテーブル名指定
- set_table_name '<所要のテーブル名>'
- コントローラ
- ビュー
- show.html.erb 以外は要らない
- show.html.erb 所要のテーブルのフィールド値表示。Edit、Backへのリンクは要らない
- フィールド名は所要のテーブルのものを指定
- route.rb
- 末尾の map.connect ':controller/:action/:id'、map.connect ':controller/:action/:id.:format' をコメントアウト
- 先頭 map.resources :arests, :only => [:show]
- :only => [:show] として参照以外のルーティングをつぶす
- 基本認証
- 流石に認証はしましょう、Basic Authentication,
- コントローラにて before_filter と authenticate_or_request_with_http_basic
- メソッド定義後掲
そのコントローラはこんな感じ
class ArestsController < ApplicationController before_filter :basic_authentication # GET /arests/1 # GET /arests/1.xml def show #@arest = Arest.find(params[:id]) @arest = Arest.find_by_office_code(params[:id]) if @arest then respond_to do |format| format.html # show.html.erb format.xml { render :xml => @arest } end else# if @arest render :text => '見付りませんでした', :status => 404 end # if @arest end private def basic_authentication authenticate_or_request_with_http_basic('AResT') do |user, password| [user, password] == ['arest', 'restful'] end # authenticate_or_request_with_http_basic('AResT') do |user, password| end # def basic_authentication end
一方 ActiveResourceクライアントはこんな感じ
class AR < ActiveResource::Base self.site = 'http://localhost:3000/' self.element_name = 'arest' self.user = 'arest' self.password = 'restful' end
クラス名称を AResTサービス側とあわせる事が出来れば element_name の設定は不要。
これで一応出来るんだけど、テストどうしよう。RSpecの準備はしてるんだけどテスト用のデータベースをどうしたものか分からないでいる。
どうしたもんかなあ。
その日のうちに追記
テストはそうか、モックとスタブを使って外部接続に被せればいいのか。