Ruby: Define a class definition at runtime?

Now I have a strange, probably with rails ... class is defined somewhere, and I can not find it. Grepping for class ClassName could not find it, but it definitely exists when I load the rails console. It's just a vanilla class inherited from the Object, with something else undefined ... pretty boring. So, I would like to know where this class constant was originally defined from the rails console. In other words, something print the value "__ FILE __" when this class was declared. I feel that some type of metaprogramming should make this possible.

I thought just doing

ClassName.class_exec { __FILE__ }

But it always always gives me the current file.

+3
source share
1 answer

The hook method inherited, if defined, is 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
+5
source

Source: https://habr.com/ru/post/1740686/


All Articles