携帯用に入力モード指定ヘルパー
mobile on railsというプラグインを入れてみたけど、これはとても便利。しかし、これには携帯の入力モードを指定できるようなコードは無かったっぽいので、その辺りを自作。
まず、app/helpers/mobile_tag_builder.rbというファイルを作成して、中身を下記のように記述
class MobileTagBuilder < ActionView::Helpers::FormBuilder def text_field (field, options = {}) if options.has_key?(:mobile_input_style) if @template.controller.request.mobile_carrier == ActionController::Mobile::DoCoMo options[:istyle] = mobile_input_style_by_carrier(options[:mobile_input_style]); elsif @template.controller.request.mobile_carrier == ActionController::Mobile::AU options[:istyle] = mobile_input_style_by_carrier(options[:mobile_input_style]); elsif @template.controller.request.mobile_carrier == ActionController::Mobile::SoftBank options[:mode] = mobile_input_style_by_carrier(options[:mobile_input_style]); end options.delete(:mobile_input_style) end super(field, options) end private def mobile_input_style_by_carrier (input_style) # ひらがな if input_style == :input_style_hiragana if @template.controller.request.mobile_carrier == ActionController::Mobile::SoftBank :hiragana else :'1' end # カタナカ elsif input_style == :input_style_katakana if @template.controller.request.mobile_carrier == ActionController::Mobile::SoftBank return :katakana else :'1' end # 半角カタナカ elsif input_style == :input_style_hankakukana if @template.controller.request.mobile_carrier == ActionController::Mobile::SoftBank :hankakukana else :'2' end # 英字 elsif input_style == :input_style_alphabet if @template.controller.request.mobile_carrier == ActionController::Mobile::SoftBank :alphabet else :'3' end # 数字 elsif input_style == :input_style_numeric if @template.controller.request.mobile_carrier == ActionController::Mobile::SoftBank :numeric else :'4' end # なんでも elsif input_style == :input_style_any if @template.controller.request.mobile_carrier == ActionController::Mobile::SoftBank :any else :'1' end # メールアドレス elsif input_style == :input_style_emailaddr if @template.controller.request.mobile_carrier == ActionController::Mobile::SoftBank :emailaddr else :'3' end # 電話番号 elsif input_style == :input_style_phonenumber if @template.controller.request.mobile_carrier == ActionController::Mobile::SoftBank :phonenumber else :'4' end # url elsif input_style == :input_style_url if @template.controller.request.mobile_carrier == ActionController::Mobile::SoftBank :url else :'3' end end end end
ソフトバンクの入力モードの指定が一番多いので、それを基準にして、ドコモとAUはマッピング。
requestオブジェクトをどうやって参照すれば良いのかちょい悩んだが、@templateインスタンス経由でアクセスできた。これは素直に本読めば普通に書いてある事だった。
とりあえず、このあとはビューで、下記のようにして呼び出し
<% form_for :signup, :url => { :action => :signup }, :builder => MobileTagBuilder do |form| %> <%= form.text_field :email, :size => 20, :maxlength => 255, :mobile_input_style => :input_style_alphabet %>
これが正しいやり方なのかどうか分からないけど、とりあえず動いているみたい。絶対ruby的な書き方じゃないだろうし…