Rails1.1: FormBuilderの使い方。

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する。
こんなところでしょうか。 つかってみるとなかなか便利です。 是非お試しあれ。

Related posts:

07.27.08/12am

No comments yet

trackback uri
  • ajax-loading
  • ajax-loading
  • ajax-loading

Leave a Comment

You can use these tags: <code>, <i>, <em>, <strong>, <a>

About

Author:yuin(http://inforno.net/)

文学部文化学科卒という生粋の文系趣味プログラマ。

主にRuby、Javascript、PHP、JAVA,Python,C,Scala,Schemeなどを使っています。今はPythonな感じかもしれない。今後作曲活動なども復活するかもしれない。

Pages