AR: add attribute to model

Hi!

Well, I thought this was easy, but for some reason it won’t work…
Here is what I want to do:

I am working on an API to a large database. The basic mapping is done,
but I want to implement some convenience methods that take information
for one object and does some calculations with it. The result should be
accessible as attribute.

So in a simple example:

We have an object that has a start and a stop attribute, i.e. columns in
the table. Now I want to know the distance, but directly via an readable
attribute.

Class Something

attr_accessor :distance

def initialize
@distance = self.stop-self.start
end

end

However, if I use my_object.distance, it returns nil…

What am I doing wrong?

P.S. I also tried
def initialize(distance) - but figured that only makes sense if I
specifically create a new object, not if the attribute is created from
within the class. Didn’t work either, anyway.

Cheers,

Marc

On Sep 17, 7:32 am, Marc H. [email protected]
wrote:

So in a simple example:
@distance = self.stop-self.start
end

If that’s an ActiveRecord objectg, not calling super (and changing the
signature of initialize) is a bad thing. you could avoid that
altogether with

def distance
@distance ||= stop - start
end

Fred

Frederick C. wrote:

On Sep 17, 7:32�am, Marc H. [email protected]
wrote:

So in a simple example:
� @distance = self.stop-self.start
�end

If that’s an ActiveRecord objectg, not calling super (and changing the
signature of initialize) is a bad thing. you could avoid that
altogether with

def distance
@distance ||= stop - start
end

Fred

bangs head against wall

Thanks a lot, should have thought of that myself…sometimes it’s right
there in front of you :wink: