ruby - Namespaced model in Rails generating NameError: uninitialized constant -
i have folder structure this:
app/ models/ bar/ foo.rb connection.rb foo.rb
connection.rb
"abstract class" connecting database, so:
class bar::connection < activerecord::base self.abstract_class = true establish_connection "outsidedb_#{rails.env}" end
bar/foo.rb
accessing foos
table outsidedb
, so:
class bar::foo < bar::connection end
and foo.rb
accessing foos
table app's db, so:
class foo < activerecord::base end
from rails console if foo.first
or bar::foo.first
things behave expect in first entry foos
table of app db , external db, respectively.
however, if try access foo
within bar/foo.rb
following:
class bar::foo < bar::connection def self.test bar::foo.first #=> works foo.first #=> nameerror: uninitialized constant bar::foo::foo end def self.other_test foo.parent #=> object foo.superclass #=> activerecord::base object::foo.first #=> works activerecord::base::foo.first #=> works, "warning: toplevel constant # foo referenced activerecord::base::foo end end
i can things working, i'm looking sounder understanding of what's going on. i'm assuming i'm missing between ruby's constant/class evaluation , rail's builtin auto-loading...
- what
.parent
returning (not 'parent' class)? - why error in
.test
, don't in rails console? - why
object::foo
seem work? right thing do? - why
activerecord::base::foo
work, warning? - there more rails way i've done without renaming 1 of
foo.rb
classes?
i'm on rails '3.2.13'
, ruby 1.9.3-p194
, know!
your problem can fixed with
::foo.first
here ::foo
indicating class foo
in top namespace.
you problem comes fact, there foo
class in namespace (bar
) working in. should explicit.
as question why object::foo
works (with warnings), it's (less) known behaviour of name lookup in ruby. please see this article more details.
Comments
Post a Comment