Vito Vito - 6 months ago 8
Ruby Question

saving an object value passed by function

I have the folliwing code:

class LogFactory < ActiveRecord::Base
after_initialize :inizializza
MESSAGENOTDEFINED = "Msg"


def inizializza
self.happened = Time.current
self.messaggio = MESSAGENOTDEFINED
end


def setMessage(messaggio)
logger = LogFactory.new(:messaggio => messaggio, :happened => self.happened)
logger.save
end
end


The problem is in the
messaggio
variable. I mean, even if i use the param messaggio in the
.new(:messaggio => messaggio,..
rails still use the
MESSAGENOTDEFINED
constant defined during the initialization.
Why?

Answer

Cause you assign MESSAGENOTDEFINED to messaggio after object initialization. When you do something like .new(:messaggio => 'my_messaggio', ...), there are 2 steps:

  1. Initialization. On this step messaggio will assign with 'my_messagio'.
  2. after_initialize callback executing. On this step messaggio will assign with MESSAGENOTDEFINED anyway, according to your code.

It looks like you want use something like this:

def inizializza
  happened ||= Time.current
  messaggio ||= MESSAGENOTDEFINED
end  

This means that MESSAGENOTDEFINED will assign to messaggio only if it falsey or has not initialized yet. Also, both self are redundant.

Comments