views:

443

answers:

4

I have problem in my model. I want method to use another property of model but before using it I want another method to be executed (to make property have value). Here is an example:

 def medthod_one=(val)
   self.value = val
 end

 def method_two
   self.second_value = self.value / 2 #just for example
 end

So, in my case self.second_value is invalid because self.value is not set yet. How to change those methods execution sequence after submitting create form for this model?

+1  A: 

Why don't you do this:

def method_one=(val)
  self.value = val
  self.second_value = val / 2
end

On the other hand, if second_value always depends on self.value, you can implement it as a read-only property:

def second_value
  self.value / 2
end
Can Berk Güder
any reason in particular for the downvote?
Can Berk Güder
+3  A: 

It is hard to come up with an elegant solution when you only provide foo-bar examples instead of actual code, but my guesswork tells me that you probably want something like this:

def som_setter=(val)
  self.value = val
end

def method_two
  return unless self.value
  # perform calculations with 'self.value'.
end
August Lilleaas
I was going to suggest a before_filter, but since the prerequisite is an assignment (which presumably is called from outside the class), your solution is preferable.
Sarah Mei
+1  A: 

I am not too sure I follow your question, but maybe taking a look at active record callbacks would help. http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html

I think you may need to reword this question.

Tony
A: 

I've absolutely the same problem here: description is empty while being called from count=(). Would you recommened the same unless .. construct or is there a cleaner way?

Actual code:

def description
   puts "Retr desc of " + @description.to_s + "\n"
   @description
end

def description=(input)
   @description=input
   puts "Set desc to " + @description + "\n"
end

def count
   self.machines.count
end

def count=(input)
  i = 1 
  machines = []

  while i <= input.to_i
     name = sprintf "%s%0.2d", self.name.downcase, i
     puts "Creating in model " + name + " with desc=." + description.to_s + ".\n"
     machines << { :name => name, :description => self.description, :usable => true } 
     i += 1
  end 
  self.machines_attributes = machines
end

The result looks like this:

Retr desc of
Creating in model u1232301 with desc=..
Retr desc of
Retr desc of
Creating in model u1232302 with desc=..
Retr desc of
Retr desc of
Creating in model u1232303 with desc=..
Retr desc of
Set desc to zweimalgleich3
Nico Schottelius