matsuda
10/21/2010 - 3:40 AM

携帯で link_to (url_for) のパラメータに日本語が含まれている場合に、適切な文字コードに変換する

携帯で link_to (url_for) のパラメータに日本語が含まれている場合に、適切な文字コードに変換する

module ActionView
  module Helpers
    module UrlHelper
      def url_for_with_jpmobile(options = {})
        if !options.nil? && options.is_a?(Hash)
          if request && (mobile = request.mobile) && !(mobile.instance_of?(Jpmobile::Mobile::Vodafone)||mobile.instance_of?(Jpmobile::Mobile::Softbank))
            options = options.inject({}){ |result, option|
              result[option[0]] = convert_multibyte_with_mobile(option[1])
              result
            }
          end
        end
        url_for_without_jpmobile(options)
      end
      alias_method_chain :url_for, :jpmobile

      private
      def convert_multibyte_with_mobile(params)
        if params.is_a?(String)
          NKF.nkf('-m0 -x -Ws', params)
        elsif params.is_a?(Hash)
          params.inject({}) do |result, param|
            result[param[0]] = convert_multibyte_with_mobile(param[1])
            result
          end
        elsif params.is_a?(Array)
          params.inject([]) do |result, param|
            result << convert_multibyte_with_mobile(param)
            result
          end
        else
          params
        end
      end
      
    end
  end
end