Question

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.

Was it helpful?

Solution

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

OTHER TIPS

Beartech's answer is right, but let me explain why:

attr_accessor creates setter & 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 created

Your problem is that you're relying on attr_accessor to persist between object instances, which means the data won't persist between requests. As beartech explained, the way to fix this is to somehow "store" the data inside the start_time method, which is best done when you initialize the object / class

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top