ActiveResourceでauth_token的なトークンで認証する方法

Rails4からは正式にプリインストール対象から外れたActiveResourceではありますが、アクセス先が絵に描いたようなRESTfulAPI、とりわけ開発者が内情を知ってるRailsアプリ間の連携等では今なお大いに力を発揮するもの。

しかし、

http://example.com/posts.json?auth_token=TOOOOKEN

このような形でのトークンの認証には対応していない。
そこで、

blog.mmmcorp.co.jp

を大変参考にさせていただき、モンキーパッチをあて、トークン認証に対応させる。

ActiveResourceが発行するURLのクエリーストリングを生成するメソッド、

def query_string(options)
        
  "?#{options.to_query}" unless options.nil? || options.empty?

end

というのがあるので、これをオーバーライドする。

全体ではこうなる。

class ActiveResource::Base
  class << selfdef query_string(options)

      if auth_token

        options.store(:auth_token, auth_token)

        "?#{options.to_query}" unless options.nil? || options.empty?

      elseraise ArgumentErrorendend
    def auth_tokenreturn @auth_token if defined?(@auth_token)

      nilend
    def auth_token=(auth_token)

      @auth_token = auth_token

    endend

end

下2つが単純な属性"auth_token"に対するゲッター、セッターメソッド。そしてquery_stringメソッドを、発行するURLのクエリーストリングになるハッシュ"options"にauth_tokenの要素を追加し、ない場合はArgumentErrorの例外を発生させるようにした。

このパッチを、Railsではlib配下等、読み込み対象ディレクトリに設置し、

class Post < ActiveResource::Base
  self.site = "http://example.com"
  self.auth_token = "TOOOOOOOOKEN"
  self.format = :xml
  self.timeout = 15
end

Post.all

このようにモデル側を実装すれば、トークンでの認証に対応が可能。

(当パッチはActiveResourceすべての処理において検証はしておりません。
ご利用の際はご注意ください。)