RousseauAlexandre RousseauAlexandre - 3 months ago 9
Ruby Question

Pointer on class object

In my Ruby model I want to apply default value on somes properties on my

Recipe
. So I added an
before_save
callback to apply it: This is my Recipe model:

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


It's pretty work but I want to factorize it like this:

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


But it doesn't work. How can I loop on "pointer" on my object propertie?

Answer

it won't work because you refer strictly to value, thus your override doesn't work as expected. you may try this:

[:t_baking, :t_cooling, :t_cooking, :t_rest].each { |t_time|
  self.send("#{t_time}=".to_sym, zero_time) unless self.send(t_time).present?
}
Comments