Reputation: 15365
I'm having an odd probably with rails right now... a class is being defined somewhere, and I can't find it. Grepping for "class ClassName" hasn't managed to locate it, but it's definitely there when I load up the rails console. It's just a vanilla class inheriting from Object with nothing else defined... quite boring. So, what I'd like is a way to figure out where this class constant was originally defined from the rails console. Something to print out the value of '__ FILE __' when this class was declared, in other words. I feel like some type of metaprogramming should make this possible.
I thought of just doing
ClassName.class_exec { __FILE__ }
But this just always gives me the current file.
Upvotes: 3
Views: 1330
Reputation: 107999
The hook method inherited
, if defined, gets called whenever a subclass is created. Therefore:
#!/usr/bin/ruby1.8
class Object
def self.inherited(child)
target_class = "Child"
raise "#{target_class} defined" if child.name == target_class
end
end
class Parent
end
class Child < Parent # => /tmp/foo.rb:6:in `inherited': Child defined (RuntimeError)
# => from /tmp/foo.rb:13
end
Upvotes: 5