Attributes and views

Hello,

I always have the same kind of design problem, which I am not sure how
to solve correctly:

  • say I have a variable, “status”, which I want to calculate once in my
    controller, and access a couple of times in my view
  • “status” variable initialization could happen in a subclass,
    overriding the regular method for that

What I do now is using an instance variable @status, which is set in a
dedicated method ‘set_status’, which can be overriden in subclasses if
needed. I then can access @status from methods of my controller or from
the view. But is that the best way? I tried to find something with
attributes, but I’m not sure…

What do you think?

Yannick M. http://www.inma.ucl.ac.be/~majoros
Informaticien UCL/INMA-MEMA
4, avenue G. Lemaître
B-1348 Louvain-la-Neuve
Tel: +32-10-47.80.10
Fax: +32-10-47.21.80

Hello Yannick.

I don’t believe a model’s status should be calculated in the controller.

What if you want to use the model outside of a web app someday? Are you
going to duplicate the code somewhere else and maintain that code in
parallel forever?

It would seem to me that you’d trying for optimization here, avoiding
recalculating status each time it’s used. Is the calculation very
expensive? If not, don’t optimize it until it hurts!

If it is expensive, you could easily write something like this:

in model:

def status
return @the_status unless @the_status.nil? # return cached status
@the_status = # perform expensive status calculation here
end


– Tom M.