AResTサービス

ActiveResource CompaTible な RESTful API を考える。「Railsレシピブック 183の技」を参考に。

ちょいと必要があって、既存DB(テーブル)への参照のみの AResTサービスを作る、テーブル一つ分だけの。

  1. Railsアプリケーション作成
  2. 下準備
    1. script\generate cucumber
    2. script\generate spec
  3. databese.yml
    1. 取り敢えず developmentのデータベースコネクション定義を所要の既存DB向けのものに
  4. script\generate rspec_scaffold <適当なモデル名> (大文字小文字単数形注意)
  5. DB定義
    1. マイグレートファイル削除
    2. rake db:migrate
      1. 何も起きない
  6. モデル定義部分にてテーブル名指定
    1. set_table_name '<所要のテーブル名>'
  7. コントローラ
    1. GET以外のコントローラメソッドをつぶす、一覧もいらない。コメントアウトでも削除でも
    2. GET の showアクションのメソッド定義後掲
      1. find を find_by<所要の参照用フィールド名> に、フィールド名は所要のテーブルのもの、Rails側では特に指定していないもの
      2. 見付らなかった時対策に render
  8. ビュー
    1. show.html.erb 以外は要らない
    2. show.html.erb 所要のテーブルのフィールド値表示。Edit、Backへのリンクは要らない
      1. フィールド名は所要のテーブルのものを指定
  9. route.rb
    1. 末尾の map.connect ':controller/:action/:id'、map.connect ':controller/:action/:id.:format' をコメントアウト
    2. 先頭 map.resources :arests, :only => [:show]
      1. :only => [:show] として参照以外のルーティングをつぶす
  10. 基本認証
    1. 流石に認証はしましょう、Basic Authentication,
    2. コントローラにて before_filter と authenticate_or_request_with_http_basic
    3. メソッド定義後掲

そのコントローラはこんな感じ

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の準備はしてるんだけどテスト用のデータベースをどうしたものか分からないでいる。
どうしたもんかなあ。

その日のうちに追記

テストはそうか、モックとスタブを使って外部接続に被せればいいのか。