Reputation: 5603
My model looks like this:
class Job < ActiveRecord::Base
attr_accessor :start_time
def start_time
self.start_time = Time.now
end
def elapsed_time
end_time = Time.now
elapsed = end_time - self.start_time
end
end
I want to measure the elapsed time, and self.start_time
exists within the start_time
method. However, in my elapsed_time
method, self.start_time
is nil. Why is that?
I am using rails 4.1.0 and ruby 2.0.0.
Upvotes: 0
Views: 1065
Reputation: 76774
Beartech
's answer is right, but let me explain why:
attr_accessor
createssetter
&getter
methods for your model. Just like how db attributes are defined, these create the methods which you call on an object (@object.method
), meaning they are only created when your object is createdYour problem is that you're relying on
attr_accessor
to persist between object instances, which means the data won't persist between requests. Asbeartech
explained, the way to fix this is to somehow "store" the data inside thestart_time
method, which is best done when you initialize the object / class
Upvotes: 0
Reputation: 6411
You need to define start_time
when the job object is created using initialize:
class Job < ActiveRecord::Base
attr_accessor :start_time
def initialize
self.start_time = Time.now
end
def elapsed_time
end_time = Time.now
elapsed = end_time - self.start_time
end
end
If you don't want start_time
to be tied to when the job is initialized, then you need to create an instance variable to hold the start time, and reference that when you call the elapsed_time
method:
class Job < ActiveRecord::Base
attr_accessor :start_time
def start_time
@start_time = Time.now
end
def elapsed_time
end_time = Time.now
elapsed = end_time - @start_time
end
end
Upvotes: 1