Rails1.1: FormBuilderの使い方。

Rails1.1にはFormBuilderというものがあります。
でもいまいちAPIマニュアルで説明が不足していて、なんだかなあ、という感じ。 こういうときはテストをみるのが一番ですね。

テストを参考にどういう風に使うのか、定義してみます。

RUBY:
  1. class LabellingFormBuilder <ActionView::Helpers::FormBuilder
  2.   include ApplicationHelper
  3.   include ActionView::Helpers::TagHelper
  4.   include ActionView::Helpers::AssetTagHelper
  5.   include ActionView::Helpers::FormTagHelper
  6.   #... and other heplers etc.
  7.  
  8.   def initialize(*args)
  9.     super
  10.   end
  11.  
  12.   (field_helpers - %w(hidden_field)).each do |form_element|
  13.     class_eval %Q{
  14.       def #{form_element}(label,opt = {}, *args)
  15.         unless opt.is_a?(Hash)
  16.           args.unshift(opt)
  17.           opt = {}
  18.         end
  19.         opt = {:for=> @object_name.to_s+'_'+args.first.to_s}.update(opt)
  20.         options = (args.last.is_a?(Hash)) ? args.pop : {}
  21.         args.push(options)
  22.         content_tag('label', label, opt) + super(*args)
  23.       end
  24.     }
  25.   end
  26. end

使い方は

RUBY:
  1. <% form_for :person, @person, :url => { :action => "update" }, :builder => LabellingFormBuilder do |f| %>
  2.   <%= f.text_field "苗字", :first_name %>
  3.   <%= f.text_field "名前", :last_name %>
  4. <% end %>

という具合に。

ポイントは

  • ActionView::Helpers::FormBuilderを継承する(当たり前)
  • (field_helpers - %w(hidden_field))という感じで、hidden_field以外のメソッドをオーバーライドする。もちろんオーバーライドしたいものだけでもかまわないですけど。
  • ヘルパーのメソッドを使いたい場合は適切なヘルパーをincludeする。

こんなところでしょうか。 つかってみるとなかなか便利です。 是非お試しあれ。

Posted at 9pm on 06/08/06 | no comments | Tags : read on

ActiveSupportのObject#with_optionsの使いどころ

個人的にActiveSupportが大好きなわけですが。

1.1で追加されたwith_optionsがRouting以外でどーもカッコいい使いどころがなーとおもっていたんですが

RUBY:
  1. with_options(:if => :validate_password?) do |me|
  2. me.validates_format_of :password #...
  3. me.validates_length_of :password # ...
  4. me.validates_confirmation_of :password #...
  5. me.validates_presence_of :password#...
  6. end


こんなキモイ使い方があった。もちろん、ActiveRecordのバリデーション。よくあるパターンで、パスワードはハッシュで保存しあって、createしたときやパスワード変更したときはバリデーションするんだけどそれ以外はしない、みたいなとき。

まぁ、やっぱり一番カッコいいのはto_procなんですけど。

Posted at 5pm on 06/05/06 | no comments | Tags : read on

About

about me
yuin()
文学部文化学科卒という生粋の文系趣味プログラマ。
ベンチャー企業でアルバイトを経て、某大手企業で働いてます。    
主にRuby、Javascript、PHP、JAVA,Python,C,Scala,Schemeなどを使っています。
今はPythonな感じかもしれない。今後作曲活動なども復活するかもしれない。

Pages