Search code examples
ruby-on-railsrubymodelattr-accessor

Rails 4 attr_accessor doesn't work across multiple methods


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.


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