Guard Ruby classes with class-level metaprogramming against multiple loads

Ruby require’s quirk is that, in general, it will only download one file once, if that file is accessible through several paths (for example, symbolic links), it can be requiredseveral times. This causes problems when there are such things as metaprogramming at the class level, or in general code that should be executed only once when loading a file, executing several times.

Is there a way, from within the definition of a Ruby class, to determine if a class has been previously defined? I thought that they could defined?or Object.const_getcould tell me, but from them it looks like as soon as a class is defined, as soon as it opens.

+4
source share
2 answers

This is not the answer to your question in the second paragraph, but the solution to the problem in your first paragraph. In fact, you cannot avoid multiple file downloads by checking if a class has already been defined.

Instead of this:

require some_file_name

make:

require File.realpath(some_file_name)

Thus, different symbolic links pointing to the same real file will be normalized for the same real file name, and therefore their multiple loading will be correctly filtered using require.

Cf. this question and the answer to it.

+1
source

, , , , .

, , , . :.

class Foo
  unless @__executed__
    def bla; end
    puts 'Test'
  end
  @__executed__ = true
end
0

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


All Articles