Rails1.1にはFormBuilderというものがあります。
でもいまいちAPIマニュアルで説明が不足していて、なんだかなあ、という感じ。 こういうときはテストをみるのが一番ですね。
テストを参考にどういう風に使うのか、定義してみます。
::ruby class LabellingFormBuilder < ActionView::Helpers::FormBuilder include ApplicationHelper include ActionView::Helpers::TagHelper include ActionView::Helpers::AssetTagHelper include ActionView::Helpers::FormTagHelper #... and other heplers etc. def initialize(*args) super end (field_helpers - %w(hidden_field)).each do |form_element| class_eval %Q{ def #{form_element}(label,opt = {}, *args) unless opt.is_a?(Hash) args.unshift(opt) opt = {} end opt = {:for=> @object_name.to_s+'_'+args.first.to_s}.update(opt) options = (args.last.is_a?(Hash)) ? args.pop : {} args.push(options) content_tag('label', label, opt) + super(*args) end } end end
使い方は
::ruby < % form_for :person, @person, :url => { :action => "update" }, :builder => LabellingFormBuilder do |f| %> < %= f.text_field "苗字", :first_name %> < %= f.text_field "名前", :last_name %> < % end %>
という具合に。
ポイントは
- ActionView::Helpers::FormBuilderを継承する(当たり前)
- (field_helpers - %w(hidden_field))という感じで、hidden_field以外のメソッドをオーバーライドする。もちろんオーバーライドしたいものだけでもかまわないですけど。
- ヘルパーのメソッドを使いたい場合は適切なヘルパーをincludeする。