2012/04/24

[rails]establish_connectionで接続先DBを変更する。

開発中の一連のシステムは、Rails3によるアプリを複数立ち上げ、 全て同じデータベースを参照している。
データベースは、その中の1つが管理(schemaや、migration)し、 他のアプリは、そのデータベースに接続する。

データベースを管理しないアプリ側では以下のコードを実装し、 接続先を変更する。
{Rails.root}/lib/custom_connection.rb

  module CustomConnection

    def establish_connection_to_other
      case Rails.env
      when "development"
        establish_connection :other_development
      when "test"
        establish_connection :other_test
      when "staging"
        establish_connection :other_staging
      when "production"
        establish_connection :other_production
      end
    end

  end
  ActiveRecord::Base.send(:extend, CustomConnection)

{Rails.root}/config/initializers/config.rb

  require 'custom_connection'
  ActiveRecord::Base.establish_connection_to_other

config/database.ymlには、 other_development, other_test, other_staging, other_productionの 定義が必要になる。

2012/04/22

curlでBasic認証超え

curlで、Basic認証を超えるには、
  $curl --basic --user <username>[:password] url
のオプションをつける。

2012/04/05

[rails]kaminari

rails3で、リスト形式の画面をページングしたかった。
will_paginate というgemがあることは知っていたが、
rails3系(実際に適用したかったのは3.1.3)で使えるのかわからなかったので、
amatsuda氏の「kaminari」を使ってみた。

恐ろしく簡単で、2hほどでページングが実装できた。
便利だと思ったのは、ARのscopeに対してページングができること。
ちっともハマらずAjaxなリクエストにも容易に対応できた。
これはスグレモノですね!