ActiveRecord - フォーマット
Posted by nanki Wed, 27 Dec 2006 12:09:00 GMT
小分けにしないとサーバが止まる・・・
model_formatter
- 特定のカラムを、フォーマット付きでアクセス。
formatted_weightで、フォーマット済みのweightにアクセス。- フォーマット済み属性の名前は、
:formatted_attr,:prefixで変更。 class Widget < ActiveRecord::Base # FormatInteger という名前のFormatterでフォーマットを指定 # :boolean, :currency, :decimal, :integer, :percent, :phone が定義済み # :as には、Formatterのインスタンスも指定できる format_column :weight, :as => :integer # Procを使って format_column :weight, :formatted_attr => :formatted_weight, :options => {:delimiter => ','}, :from => Proc.new{|attribute, options| ... }, :to => Proc.new{|str, options| ... } # ブロックによる定義も format_column :weight do def from(attribute, options) # ... end def to(str, options) # ... end end end w = Widget.new(:weight => 12345) w.formatted_weight # => 12,345 # 書き込みもできる! w.formatted_weight = '54,321' w.weight # => 54321
auto_convert_fields
attribute=を定義。class MyModel < ActiveRecord::Base # name=, :text= の前に、TextHelper#strip_tags をはさむ。 auto_convert :name, :text, :with => :strip_tags # 同じ auto_convert :name, :text do |value| strip_tags(value) end end
