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

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

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 Cheung wrote: