jpmobile のmobile_filter を部分的に無効にする(強引な方法)メモ

使える状況が限られているし、jpmobile自体をいじるし、グローバル変数を汚すしで、
極悪な解だが、一応メモしておく。


たとえば下のように、親コントローラに mobile_filter を記述し、それを継承した子コントローラがいくつかあるとする

# 親
class MobileController < ApplicationController
  mobile_filter :hankaku => true
end

# 子
class HogeController < MobileController
  def index
  end

  ...
end

class FooController < MobileController
  def index
  end

  ...
end

で、HogeControllerでは、半角全角変換をしたく無い場合にどうするか。


真っ当な方法としては、mobile_filter の宣言を 親コントローラであるMobileControllerに記述することをやめて、
それぞれのコントローラに記述する方法

# 親
class MobileController < ApplicationController
end

# 子
class HogeController < MobileController
  def index
  end

  ...
end

class FooController < MobileController
  mobile_filter :hankaku => true

  def index
  end

  ...
end

たしかにこれでもよいが、さらにHogeControllerの中の
index のみ半角全角変換を外したい場合は、どうすればよいか。
(言い換えると、HogeController でも、index以外では半角全角変換したい場合はどうしたらよいか)


ここからが極悪解だが、
mobile_filter の宣言部分( jpmobile/lib/jpmobile/filter.rb )を以下のようにいじる

class ActionController::Base #:nodoc:
  def self.mobile_filter(options={})
    options = {:emoticon=>true, :hankaku=>false}.update(options)

    if options[:emoticon]
      around_filter Jpmobile::Filter::Emoticon::Outer.new
    end
    around_filter Jpmobile::Filter::Sjis.new
    if options[:emoticon]
      around_filter Jpmobile::Filter::Emoticon::Inner.new
    end
    if options[:hankaku]
#      around_filter Jpmobile::Filter::HankakuKana.new    # この1行をコメントアウトし、以下2行を追加
      $jpmobile_filter_hankakukana = Jpmobile::Filter::HankakuKana.new    # グローバル変数に半角全角変換フィルタのインスタンスを格納して取っておく
      around_filter $jpmobile_filter_hankakukana
    end
  end
end

なおこの例では、半角全角変換のみ無効にしようとしているので、1つしかグローバル変数に入れていないが、
全てを無効にしたいのであれば、Jpmobile::Filter::Emoticon::outer, Jpmobile::Filter::Sjis, Jpmobile::Filter::Emoticon::Inner も入れておく必要があると思われる


これで、フィルタのインスタンスが格納されているので、skip_filterやそのオプションが使用可能となった。
つまり、外したいコントローラで、外したいアクションをskip_filterで指定すれば良い

# 親
class MobileController < ApplicationController
  mobile_filter :hankaku => true
end

# 子
class HogeController < MobileController
  # HogeController の index のみ半角全角変換フィルタをskip
  skip_filter $jpmobile_filter_hankakukana, :only => :index

  def index
  end

  ...
end

class FooController < MobileController
  def index
  end

  ...
end

条件として、グローバル変数を使っているせいで、mobile_filter 宣言は複数回不可能
(どこか1つだけ、正しく動作して、それ以外は効かなくなる)


もっと良い方法があったら教えてくださいorz


ちなみに、rails は 2.3.5 です。