ActiveRecord - フォーマット
小分けにしないとサーバが止まる・・・
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,
<span class="sy">:formatted_attr</span> => <span class="sy">:formatted_weight</span>, <span class="sy">:options</span> => {<span class="sy">:delimiter</span> => <span class="s"><span class="dl">'</span><span class="k">,</span><span class="dl">'</span></span>}, <span class="sy">:from</span> => <span class="co">Proc</span>.new{|attribute, options| ... }, <span class="sy">:to</span> => <span class="co">Proc</span>.new{|str, options| ... }# ブロックによる定義も format_column :weight do
<span class="r">def</span> <span class="fu">from</span>(attribute, options) <span class="c"># ...</span> <span class="r">end</span> <span class="r">def</span> <span class="fu">to</span>(str, options) <span class="c"># ...</span> <span class="r">end</span>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
0 comments »
〜へのトラックバック ActiveRecord - フォーマット