15 Jul 2011, 04:20
Generic-user-small

Noah Chase (1 post)

I’m using the ePub formatted book, so I can’t give the best page number here. Roughly p.45 – “The First Refactor”

Noel Rappin is fleshing out the StatusReport model to make the “saving a status report that has a date doesn’t override” test.

His code reads

def set_status_date
  self.status_date = Date.today if status_date.nil?
end

Instead, I expected to see

def set_status_date
  self.status_date = Date.today if self.status_date.nil?
end

, but it works as-is. I must be missing something basic here.

18 Jul 2011, 18:52
Generic-user-small

Danny O Cuiv (7 posts)

status_date is an ActiveRecord attribute, which means that the accessors are generated, specifically a setter (status_date=) and a setter (status_date). When these are invoked from outside the class, there is no ambiguity

object.status_date = Date.today and foo = object.status_date

When you want to invoke them inside the class, the getter can be called unqualified, but you need to qualify the setter (with self), because of an ambiguity in the grammar. Specifically

status_date = Date.today

would look to the interpreter like an assignment to a local variable. Obviously you can qualify the getter too. It’s just that it’s not necessary.

Danny.

19 Apr 2012, 12:28
Generic-user-small

Charles de Bueger (9 posts)

Nice explanation. Thanks Danny.

  You must be logged in to comment