ActiveRecord::Baseの項目をオーバーライトする
いまさら感のある基本な事ですが、
ある項目は値をセットするときに、エスケープしたいとか何倍したいとかするとき。
require 'cgi' Class Page < ActiveRecord::Base # uriがmigrateで定義されているとします # セッタの場合 def uri=(text) # self.uri = CGI.unescape(text) この書き方はNG(無限ループになってスタックオーバーフローを起こす) write_attribute(:text, CGI.unscape(text)) #こっちが正しい end # ゲッタの場合 def uri read_attribute(:uri) end end
ちなみに、ActiveRecord 1.15.3のActiveRecord::Baseの127行目にこんな記述が。
# == Overwriting default accessors # # All column values are automatically available through basic accessors on the Active Record object, but some times you # want to specialize this behavior. This can be done by either by overwriting the default accessors (using the same # name as the attribute) calling read_attribute(attr_name) and write_attribute(attr_name, value) to actually change things. # Example: # # class Song < ActiveRecord::Base # # Uses an integer of seconds to hold the length of the song # # def length=(minutes) # write_attribute(:length, minutes * 60) # end # # def length # read_attribute(:length) / 60 # end # end # # You can alternatively use self[:attribute]=(value) and self[:attribute] instead of write_attribute(:attribute, vaule) and # read_attribute(:attribute) as a shorter form.
いままで、set_uriとかいうメソッドを作ってたのはココだけの秘密だ!
(ノ∀`)アチャー