Rails models/controllers are lazily loaded, so const_defined? might be
false even though you have a file that defines that constant. If that
constant hasn't been loaded before that check has run, it would call
the const_set instead. Using const_get will attempt to find the class
and load the file if there is one.
--
Write intention revealing code #=> http://www.clean-ruby.com
Jim Gay
Saturn Flyer LLC
571-403-0338
I thought this was mentioned in the book, but I don't have it in front
of me right now.Rails models/controllers are lazily loaded, so const_defined? might be
false even though you have a file that defines that constant. If that
constant hasn't been loaded before that check has run, it would call
the const_set instead. Using const_get will attempt to find the class
and load the file if there is one.
Bingo. Ruby's autoload has a way to ask if a constant can be
autoloaded, and I assume Rails' method does as well; ;but I wasn't
sure how reliable they are. I figured by actually letting Ruby try to
access the constant I'd be giving any autoload mechanisms the maximum
opportunity to work before falling back on a stub.
--
Avdi Grimm
http://avdi.org
I only check email twice a day. to reach me sooner, go to
http://awayfind.com/avdi
Interesting. When I need a stub Constant defined in my isolated tests
recently I've been using
Constant ||= Class.new
This has seemed to work fine whether I'm running the test in
isolation, or as part of a full test run - whether I'm stubbing an
ActiveRecord class or not!
I guess this is achieving the same thing. It give ruby the chance to
autoload the constant if it knows how to, otherwise it assigns it a
new class (or module or I suppose even an rspec stub).
Steve
--
Steve Tooke :: heavi.es
+44 7919 337 463 :: +44 20 8133 4134
skype:stevetooke :: twitter.com/tooky
Heavies Limited
Registered Number: 7612561
Registered Address: Parmenter House, 57 Tower Street, Winchester SO23 8TD