Skip to content

Instantly share code, notes, and snippets.

@jcasimir
Created March 9, 2011 04:37
Show Gist options
  • Select an option

  • Save jcasimir/861701 to your computer and use it in GitHub Desktop.

Select an option

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
@avdi

avdi commented Mar 13, 2011

Copy link
Copy Markdown

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
Copy Markdown
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
Copy Markdown
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