0
私のRubyモデルでは、私のRecipe
のsomesプロパティにデフォルト値を適用したいと思います。だから私はそれを適用するbefore_save
コールバックを追加しました:これは私のレシピのモデルである:クラスオブジェクト上のポインタ
class Recipe < ActiveRecord::Base
before_save :set_default_time
# other stuff
private
# set default time on t_baking, t_cooling, t_cooking, t_rest if not already set
def set_default_time
zero_time = Time.new 2000, 1 ,1,0,0,0
self.t_baking = zero_time unless self.t_baking.present?
self.t_cooling = zero_time unless self.t_cooling.present?
self.t_cooking = zero_time unless self.t_cooking.present?
self.t_rest = zero_time unless self.t_rest.present?
end
end
それはかなりの仕事だが、私はこのようにそれを因数分解したい:
class Recipe < ActiveRecord::Base
before_save :set_default_time
# other stuff
private
# set default time on t_baking, t_cooling, t_cooking, t_rest if not already set
def set_default_time
zero_time = Time.new 2000, 1 ,1,0,0,0
[self.t_baking, self.t_cooling, self.t_cooking, self.t_rest].each{ |t_time|
t_time = zero_time unless t_time.present?
}
end
end
しかし、それは動作しません。オブジェクトのプロパティで "ポインタ"をどのようにループできますか?
ありがとう、それは完璧に動作します! – RousseauAlexandre
素敵な、ちょっとしたトリックは、メソッド名をシンボルにキャストするのをスキップでき、 '.send'は文字列で完璧に動作することです。 – max
本当ですが、シンボルを使用することは、私が知る限り、少し効率的です。あなたのアプリの別の場所にシンボル ':foobar'を持っていれば、それらは同じ' object_id'を持っています。これは文字列には当てはまりません(ダブルメモリ割り当て) – djaszczurowski