Skip to content

Instantly share code, notes, and snippets.

@jcasimir
Created March 9, 2011 04:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jcasimir/861701 to your computer and use it in GitHub Desktop.
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
@ngauthier
Copy link

one last note:

I'd put super last, that way the lunch_id and lunch_balance columns can be overridden by params.

@jcasimir
Copy link
Author

jcasimir commented Mar 9, 2011

good call

@ngauthier
Copy link

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 .... :-)

@jcasimir
Copy link
Author

jcasimir commented Mar 9, 2011

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.

@avdi
Copy link

avdi commented Mar 13, 2011

A little extra exposure wouldn't hurt it... using build_* means you're not encoding an unnecessary assumption about what type #lunch should be.

@jcasimir
Copy link
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?

@jcasimir
Copy link
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