-
-
Save jcasimir/861701 to your computer and use it in GitHub Desktop.
class Student < ActiveRecord::Base | |
def initialize(params) | |
self.lunch = LunchTracker.new | |
self.lunch_balance = LunchTracker::STARTING_BALANCE | |
super(params) | |
end | |
end | |
# Refactoring one step further to take out the knowledge of Lunch's exact class name... | |
class Student < ActiveRecord::Base | |
def initialize(params) | |
self.build_lunch | |
self.lunch_balance = self.lunch.class::STARTING_BALANCE # Any cleaner way to pull this? | |
super(params) | |
end | |
end | |
# Pull the lunch_balance over to the LunchTracker object... | |
class Student < ActiveRecord::Base | |
def initialize(params) | |
self.build_lunch | |
super(params) | |
end | |
end |
good call
ok one last thing.
I think this is wrong:
self.lunch_id = LunchTracker.new
and that you meant:
self.lunch = LunchTracker.new
which is equivalent to:
self.build_lunch
build_<assoc> is provided by belongs_to
mmmmm .. build lunch .... :-)
You're right about pulling off the id. The build syntax is interesting, but I don't think many Rails devs would recognize it. I don't think I've used it -- but I'll investigate.
A little extra exposure wouldn't hurt it... using build_* means you're not encoding an unnecessary assumption about what type #lunch should be.
Avdi,
You're right -- people not being familiar with it was a cop-out argument, apologies Nick!
So then I was thinking about how to get the constant value out of LunchTracker without knowing the class name, instead going through the instance. Is there any better way then calling .class?
Nevermind...once I started preparing the slide I realized the real issue is that the lunch_balance belongs in the hypothetical LunchTracker object. Having it in Student is stupid -- which is why the gymnastics necessary to access the constant are ugly.
one last note:
I'd put super last, that way the lunch_id and lunch_balance columns can be overridden by params.