Created
March 9, 2011 04:37
-
-
Save jcasimir/861701 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
Author
A little extra exposure wouldn't hurt it... using build_* means you're not encoding an unnecessary assumption about what type #lunch should be.
Author
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?
Author
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.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.